Variables in C++
Variables are actually named storage places in the computer’s memory. The values that are held by these variables can change multiple times during the execution of the program.
The amount of space that a variable will occupy, its layout and the set of operations that can be applied to that variable are determined by its type.
Naming a Variable:
As per the rules a C++ variable name can have:
- Letters, digits, and the underscore character.
- It must begin with either a letter or an underscore.
- It cannot start with a number.
- Upper and lowercase letters are distinct because C++ is case-sensitive.
Valid Variable Names: _ab32, Square, sQu123, squ123,tr_89, Qwerty, r321_o, etc.
Here, sQu123 and squ123 are two different variables as C++ is a Case Sensitive language.
Invalid Variable Names Reason:
32uo Variable name cannot start with a number.
%gt ‘%’ special character not allowed.
_09** ‘*’ special character not allowed.
Qw$@ ‘$ and @’ special characters not allowed.
passw$#@ ‘$, # and @’ special characters not allowed.
Following are the types of variables in C++, as discussed in the last chapter.
|bool||Stores either value true or false.|
|char||Typically a single octet (one byte). This is an integer type.|
|int||The most natural size of integer for the machine.|
|float||A single-precision floating point value.|
|double||A double-precision floating point value.|
|void||Represents the absence of type.|
|wchar_t||A wide character type.|
The type of the variable is determined by its data type.
C++ also allows us to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes.
Variable definition in C++:
A variable definition tells the compiler where and how much storage to create for the variable.
Variable declaration in C++:
A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name, so that compiler proceed for further compilation without needing complete detail about the variable.
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
void main ()
// Variable definition:
int a, b;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
f = 70.0/3.0;
cout << f;