A variable is a symbolic name given to some information or data. Generally a variable in programming are used to store location of data stored on memory and thus also access the contents on those memory address and they are always willing to change during the time of program execution, hence they are said to have varying values.
Unlike variables in Mathematics we used which were always named shortly for easy manipulation, the variables in programming are given specific or long name to make them relatively descriptive of their usage and also help to understand easily during the development of program.
Variables can be used frequently and they can also be re-assigned values as many times as we need (generally in iterations which we will talk later).
The names given to the variables are also said to be the identifiers, i.e. we identify a value or data using a descriptive name.
Rules on declaring an identifier
Should never be a keyword
Should never start with number or special character
Can be started with alphabets or underscores
Letters with Upper case and Lower case mean different as ASCII values are different
The length of an identifier depends on what programming language we use and what restrictions they put.
Actually these names that we use for variables are converted into memory location by the compiler for program execution, so the identifiers are only meant to be understood for programmers perspective, at bottom end everything is converted into machine language which computer understands.
Lets take an example in C language on declaring a variable using a data-type:
So as the diagram says,
intrepresents a datatype,
var1represents the identifier what we say as variable name & all statements should end with a semicolon
Now talking more about datatype, each datatype has different memory allocation size in different languages.
Talking about C language, the datatypes and their sizes are as follows
|DataType||Size in Bytes||Range|
|signed char||1||-128 -> +127|
|unsigned char||1||0 -> +255|
|int||2||-32,768 -> +32,767|
|unsigned int||2||0 -> +65,535|
|long int||4||-2,147,483,648 -> +2,147,483,647|
|float||4||±37E -> ±38E|
|double||8||±37E -> ±307E|
|long double||12||±37E -> ±4931E|
Some addition of datatypes were added in C++ as follows:
And the list goes on for Java & C# and many other languages.
Lets see a variable in a diagrammatic cuboid,
So in this cube, there are three phases seen namely identifier, value/state/ and memory location which represents a complete variable. Always we should think of a variable in a cubic form.
Here var1 is the variable name, which has a value or state of “10” & stored on a memory location of “2000”.
A short program on variable arithmetic operation,
The above was the short description on variables & their usage and we can use them in multiple languages having the same architecture we seen above.