Please enable Javascript to correctly display the contents on Dot Net Tricks!

Variable

Posted On : 03 Jun 2016
Updated On : 03 Jun 2016
Total Views : 872

Variable is a name of memory location, which is use for storing value, as name variable, value of variable can change during program execution. It can store only one value at a time. You should always choose a meaningful variable name like average, number, age, total, sum etc.

Rules to define a variable

  1. A variable name can have letters (both uppercase and lowercase letters), digits and underscore only.

  2. Variable name can start with either a letter or an underscore. However, it is not good naming convention to start variable name with an underscore. It is because system name starts with underscore, variable name that starts with an underscore can clash with system keywords

  3. There is no rule on how long a variable can be but the first 31 characters of a variable are matched by the compiler. So that first 31 letters of two variables must be different.

  4. In C programming, you have to declare a variable before you can use. It is a common practice in C programming to declare all the variables at the beginning of the program.

Example

//declaration of variable
int a, b, c; 
//assigning values to variable a and b
a=10;
b=20; 
//Here variable a and b are integer, hence mathematical operations can be performed.

Types of Variable

  1. Local variable

  2. Global variable

variable in c

Local Variable

  1. The scope of a local variable will be within the statement blocks like if, if..elseif, for, while, do..while, switch etc. and function only.

  2. A local variable can not be can’t be accessed outside the statement block and function.

Global Variable

  1. The scope of global variables will be whole program. These variables can be accessed from anywhere in the program.

  2. This variable is defined outside the main function. So that, this variable is visible to main function and all other sub functions.

Example

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

int p, q, sum; //Global variables
p=20;
q=30;

void main()
{
 int a, b, add; //Local variables
 
 a=20;
 b=40;
 //sum of local variables
 add=a+b;
 printf("\n sum is", add);
 
//sum of global variables
 sum=p+q;
 printf("\n sum is", sum);
 
 getch();
}