Container / bucket for information / data, whose size in memory is determined by their data type.
|Variables are created by declaring their data type and giving them a name:||int myVar ;|
|They are then defined by assigning a value to the variable name:
Using the = assignment operator.
|myVar = 42 ;|
|Or together:||int myVar = 42 ;
char myLabel = “d” ;
The action of declaring a variable tells the compiler how much memory space is required for this variable, and giving it a name acts like an alias for its memory location.
For example, a variable of the data type int takes up 4 bytes (32 bits) of memory. When compiled and run, the program instructs the OS to allow 4 bytes of memory space for that int, and so on for all the other variables in the program.
All variables must, at least, be declared before they are used, and can be defined later. If a variable is declared after main() but attempted to be used within main(), the compiler will produce an error.
First off, we declare the variable by specify its data type and giving it a name:
int myVar ;
The use of “myVar” is simply an identifier, a label, and any alphanumeric combination can be used.
Now that the variable “myVar” has been declared, we can assign data to it, by use of a SINGLE equals = character.
*(Note that assignment uses a single = character. This often gets confused with double == characters used for equality testing)
myVar = 42 ;
Giving us the required data in the variable:
New data can be assigned to the variable, replacing the old data (which is then discarded if nothing else is done with it beforehand):
Leaving us with the new data in the variable: