In program, we need to store a value to use immediately or later or we store values after calculation. In computer memory each bit is called a memory cell (or memory location). Each memory cell consists of a address that can be in form of 0xfff3df. It is difficult to remember each and every address in a program and it’ll get more difficult when we use them repeatedly. To make the retrieval and usage of memory cell easy, we have given them names. These names are categorized following:

  1. Variables
  2. Constants

We’ll discuss constants in next lesson. Variables as the name suggests “change” a variable is the name of a memory cell whose value can be changed during the execution of program. We’ll demonstrate this by using following example


#include <stdio.h>
#include <conio.h>

void main() {
  int x;
  x=3;
  printf("Value of x: %d", x);
  x=5;
  printf("\nValue of x: %d", x);
  
  getch();
}

Note: Don’t get confused with “%d” we’ll discuss this in next lesson “Format Specifier” just remember this in this program it is used to print the value of x or specifying the data type of x..

In above example we’ve started the program from declaration of “x”. As we’ve discussed in earlier lesson data types an “int” can store only integer value the size occupied by a “int” is 4 bytes that means “x” is a variable name given to the combination of 4 bytes and it can only store integer value.

In line 2 we’re storing “3” in “x” it means now “x” memory block contains “3” as a content of that 4 bytes memory. So in 3rd line when we prints “x”, it’ll print “3”. On next line we store the value “5” in “x” so the previous value of “x” that was “3” will be replaced by the new value that is “5”. So in next line, printf() will print “5” as output.

Since the location whom we give the name “x” can hold different values of integer type during the execution of program. So that’s why “x” in this case is a variable.  This works similar as variable in math.

Thus a variable name is the name of memory location that can change during the execution of program.  A variable can only store the type of value it is declared to store i.e For example a “char” variable can only store a single character.

Rules for Constructing Variable Names:

  1. Variable name can only consist 1 to 31 character includes alphabets, numbers and underscores. Some compilers allow variable names length to 247 but it is better to manage variable name b/w 31 characters because as longer the name will be, harder it will be to remember or it’s type.
  2. First character must be alphabet or underscores.
  3. No spaces or special characters can be used in a variable name.
  4. Variable names are case sensitive e.g. “x” and “X” are 2 different variables for a compiler.
  5. Variable name must not be a reserved word or it can’t be a name that’s already used in a program.

Tip: Name the variable on it’s working like if you’re doing addition you can store sum in variable name “sum”.