C++ Variables

In this tutorial you will learn about the C++ Variables and its application with practical example.

C++ Variables

What are Variables?

A Variable is an identifier used to refer to the memory location in computer memory that holds a value for that variable, this value can be changed during the execution of the program. When you create a variable in C++, this means you are allocating some space in the memory for that variable. The size of the memory block allocated and the type of the value it holds is completely dependent upon the type of variable.

Rules for naming a variable in C++

Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Naming a variable in C++ Programming is an important task and must follow some rules, listed below –

  • Variable names can consist of letters and alphabets.
  • Keywords are not allowed to use as a variable name.
  • Blank spaces are not allowed in the variable name.
  • The first character of the variable should always be an alphabet and cannot be a digit.
  • Variable names are case sensitive i.e. UPPER and lower case are significant.
  • Special characters like #, $ are not allowed except the underscore.
  • Mathematical symbols, arrows, Unicode code points are not allowed.

Recommendation :- Variable name must be readable and should be relative to its purpose.

Declaring Variables In C++

In C++, variables must be declared before they are used. In C++, variables are declared using the data type followed by a variable name that you want to declare.




Here is an example of declaring an integer, which we’ve called counter. (Note the semicolon at the end of the line; that is how your compiler separates one program statement from another.)

This statement means we’re declaring some space for a variable called counter, which will be used to store integer data. Note that we must specify the type of data that a variable will store.

Declaring multiple variable

In C++, it is possible to declare multiple variables of same type in a single statement separated by commas, with a single type annotation as following-



Variable assignment In C++

The assignment operator (=) is used to assign values to a variable, the operand in the left side of the assignment operator (=) indicates the name of the variable and the operand in the right side of the assignment operator (=) indicates the value to be stored in that variable.



Initializing Variable In C++

In C++, it is possible to declare and assign some initial value to a variable in single statement.



Multiple assignments In C++

In C++, it is possible assign multiple variables the same value in a single statement as following-


In this tutorial we have learn about the C++ Variables and its application with practical example. I hope you will like this tutorial.