By it's definition, a variable is a place in memory that holds some information.
Some information may be numbers, characters, strings or booleans.
There are numerous ways to use and declare variables in C++. Here is the way to declare them:
type varName = initial_value;
where, in the above, type is the appropriate data type of the variable
(i.e int, double, char etc...), varName is a useful name for your variable, and the
initial value will vary when given the data type.
Here is a chart of the most used data types in C++:
| Type |
Description |
Size |
| char |
Character or small integer.
Signed range: -128 to 127
Unsigned range: 0 to 255
|
1 byte |
| short |
Short Integer.
Signed: -32768 to 32767
Unsigned: 0 to 65535
|
2 bytes |
| int |
Integer.
Signed: -2147483648 to 2147483647
Unsigned: 0 to 4294967295
|
4 bytes |
| long |
Long Integer.
Signed: -2147483648 to 2147483647
Unsigned: 0 to 4294967295
|
4 bytes |
| bool |
Boolean value. Either true or false.
Acceptable as 1 or 0 respectively.
|
1 byte |
| float |
Floating point number.
3.4e +/- 38 (7 digits)
|
4 bytes |
| double |
Double precision floating point number.
1.7e +/- 308 (15 digits)
|
8 bytes |
Let's say we want to declare and initialize 3 variables named yes, no and maybe of type bool.
Below demonstrates numerous ways to do just that:
There are different ways that variables can be declared:
Global variables
Global variables are declared outside the main function
(usually after the #include statements).
They can be accessed from anywhere in the program and there are no restrictions.
Below is a sample about this:
There, integers a and b are global to the program.
Local variables
Local variables are quite the opposite.
They can be used in between two curly braces { } for a function.
Once the closing brace appears, the variables life span is over. Below is a sample of this:
The integer a and character v are local to the main function.
If you tried using them directly elsewhere, they would not exist.
Constant variables
Constant variables can be either local or global in the program.
The restriction is that they have the same value each time, hence being constant.
A common practice is to make the constant variable name all capital letters.
You cannot change the value of constant variable directly. So here is what something may look like:
The above snippet would produce an error upon compiling. It will tell you that you cannot change
the value of a constant variable. Take my advice: leave it alone.