Variables in C

A variable is a temporary memory location that holds its data temporarily. C requires the data type of the variable to be well defined at the time of variable declaration, according on its value.

Syntax:

data_type variable_list;

Rules for using C Variables:

  • C Variable name starts with a letter or underscore only; numbers and special characters are restricted for this.
  • C Variables name can contain alphanumeric characters and underscores only.
  • C Variables name can not contain any white space within it.
  • C Variables name should not be same as any reserved word or keyword already defined in C library.

C Variables Types:

C Variable are classified according to the scope of the variable inside the code, i.e, the portion of the script where the variable can be used. These are:

Local:

Local Variables can only be accessed within the function where it is declared.

Global:

Global Variables can only be declared outside the function and can be accessed by all the functions.

Static:

Static Variables are declared with static keyword for a variable to retain its value between multiple function calls.

External:

External Variables are declared with extern keyword for a variable to be shared in multiple files.

 Automatic:

Automatic Variables can be declared with auto keyword. Although, every variable declared inside a function, by default, are automatic variables.

Example 1: Local declaration of Variables.

#include<stdio.h>
 
void main()
{
int a, b;
printf ("Enter two numbers: ");
scanf ("%d, %d",&a,&b);
printf("Sum of x+y = %i", a+b);
}

Output

Enter two numbers: 2,3
Sum of x+y = 5

Example 2: Global declaration of Variables.

#include<stdio.h>
int sum;
 
void main()
{
int a, b;
printf ("Enter two numbers: ");
scanf ("%d, %d",&a,&b);
sum = a+b;
printf("Sum of x+y = %i", sum);
}

Output

Enter two numbers: 2,3
Sum of x+y = 5
Please follow and like us:
Content Protection by DMCA.com