Variables

What is are variables in C/C++ ?

A variable is a name given to a particular "memory location" in computer’s memory.

Can you explain a bit more ?

Alright, for example:

int main()
{
    int a = 52;
}

In the above program, statement at line# 3 is a request to the computer asking “to allocate some space in its memory and store value 52 (compiler will do this translation).

Just like we humans have postal addresses to our house, office and other locations, each memory location (byte) in computer will also has its own unique address.

But it memory addresses looks different to our postal addresses, 0x16ba4b7ac this is how a memory address looks like (a hexadecimal value).

A visual representation of line# 3 is:

So, 'a' is the name given to memory address 0x16ba4b7ac.

Ok, but why do we need variables ?

Just imagine, memory addresses like above are not given a name and if programmers need to perform any operations (like add, subtract, etc.,) on value 52, it will be difficult to do everything just by using the address right ?

so, variables are required to access values and their memory locations with ease.

Why a variable is called variable ?

Because:

  • The value stored in the variable 'a' can be changed.
  • Each the program is executed variable 'a' can get entirely a different address.

Since these factories varies, it is called a ‘variable’.

Rules to create a variable:

  • Should start either with an _ (underscore) or with an alphabets (e.g: _var, var123).
  • Case sensitive (e.g: var and Var are different).
  • Cannot be same as C/C++ keywords (e.g: int, switch etc., cannot be used).

Limitations on length of a variable name:

  • In C – maximum of 32 characters long.
  • In C++ – maximum of 1024 characters long.