Explain variable declaration and rules of variables in C language

CServer Side ProgrammingProgramming

Let us first understand, what is a variable.


  • It is the name for memory location that may be used to store a data value.

  • A variable may take different values at different times during execution.

  • A variable name may be chosen by the programmer in a meaningful way, so as to reflect its function (or) nature in the program.

For example, sum, avg, total etc.

Rules for naming variable

The rules for naming a variable are explained below −

  • They must begin with a letter.

  • Maximum length of variable is 31 characters in ANSI standard. But, first eight characters are significant by many compilers.

  • Upper and lowercase characters are different. For example: total, TOTAL, Total are 3 different variables.

  • The variable is not to be a keyword.

  • White space is not allowed.

Variable declaration

The syntax and example with regards to variable declaration are explained below −


Given below is the syntax for variable declaration −

Datatype v1,v2,… vn;

Where, v1, v2,...vn are names of variables.

For example,

int sum;
float a,b;

Variable can be declared in two ways −

  • Local declaration − ‘Local declaration’ is declaring a variable inside the main block and its value is available within that block.

  • Global declaration − ‘Global declaration’ is declaring a variable outside the main block and its value is available throughout the program.


Following is the C program for local and global declaration of variables in C language −

int a, b; /* global declaration*/
main ( ){
   int c; /* local declaration*/
   - - -


Given below is a C program to find the selling price (SP) and cost price (CP) of an article −

 Live Demo

int main(){
   float CostPrice, SellingPrice, Amount; //variable declaration
   //costprice & sellingprice are variables and
   //float is a datatype
   printf("\n product cost price: ");
   scanf("%f", &CostPrice);
   printf("\n product selling price : ");
   scanf("%f", &SellingPrice);
   if (SellingPrice > CostPrice){
      Amount = SellingPrice - CostPrice;
      printf("\n Profit Amount = %.4f", Amount);
   else if(CostPrice > SellingPrice){
      Amount = CostPrice - SellingPrice;
      printf("\n Loss Amount = %.4f", Amount);
      printf("\n No Profit No Loss!");
   return 0;


The output is as follows −

product cost price : 240
product selling price : 280
Profit Amount = 40.0000
Published on 10-Mar-2021 10:25:11