In C++, all variables are declared with type. C++ forces1 you to specify the type explicitly, but doesn't force you to initialize the variable at all.
long int a = 2;
long int b = 2L;
long int c;
This code makes 3 variables of the same type long int
.
int a = 2;
int b = 2L;
int c;
This code makes 3 variables of the same type int
.
The idea of type is roughly "the set of all values the variable can take". It doesn't (and cannot) depend on the initial value of the variable - whether it's 2
or 2L
or anything else.
So, if you have two variables of different type but same value
int a = 2L;
long int b = 2;
The difference between them is what they can do further in the code. For example:
a += 2147483647; // most likely, overflow
b += 2147483647; // probably calculates correctly
The type of the variable won't change from the point it's defined onwards.
Another example:
int x = 2.5;
Here the type of x
is int
, and it's initialized to 2. Even though the initializer has a different type, C++ regards the declaration type of x
"more important".
1 BTW C++ has support for "type inference"; you can use it if you want the type of the initializer to be important:
auto a = 2L; // "a" has type "long int"
auto b = 2; // "b" has type "int"