Variables

Variables

3 | Variables


     Variable is alocate a memory location to store data. It gives name to that memory location. It can store only single type of data at a time. A variable must be declared before it can be used.


3.0 | Contents :

     1.   Rules for Naming of Variables
     2.   Variables Declaration
     3.   Assignment of Values to Variables
     4.   Classification of Variables


3.1 | Rules for Naming of Variables :

  • The first character of a variable must be an alphabet or underscore ( _ ) or dollar sign ( $ ).
  • Any type of white space you can't use in the naming of variables.
  • Names of variables are case sensitive (i.e. var is different from VAR).
  • You cannot use any keyword reserved for C language as a name of variable.


3.2 | Variables Declaration :

     The declaration of a variable is begin with the type of variable and then name of variable.

The general format is :
          data_type variable_name ;

     where, data_type is the data-type of variable
     and variable_name is the name of that variable.

     To declare multiple variables of same data-type ; the declaration begins with data-type and then names of variables seperated by comma (,).

The general format is :
          data_type var_name1,var_name2,var_name3,.....,var_namen ;

     where, data_type is the data-type of variables
     and var_name1,var_name2,var_name3,.....,var_namen are the name of those variables.

     Examples of some variables :

  • char a;
  • int num;
  • float a,b;
  • double c1,d1;
  • int n,n1,n_1;


3.3 | Assignment of Values to Variables :

     Variables declared in C can be initialized with a value also.

The general format is :
          data_type var_name = value ;

     where, data_type is the data-type of variable
     and variable_name is the name of that variable
     and value is the value given to that variable.

     Examples :

  • int a = 1;
  • float b = 1.2;
  • char c = 'A';


3.3 | Classification of Variables :

  1. Local Variables : The variables declared in a function, are called local variables and they are only usable in that funtion only.


    Example :

    #include<stdio.h>
      int main()
        {int a,b;}
      int add()
        {int m,n;}


    Here, variables a and b are only usable in the main() function, while variables m and n are only usable in the add() function.


  2. Global Variables : The variable(s) declared outside the function(s), are usable in any function of that program. These variables are called as global variables. These variables are commonly written after the preprocessor directives and before the starting of main() function.


    Example :

    #include<stdio.h>
      int a,b,c,d;
      int main()
        {     }
      int add()
        {     }


    Here, variables a,b,c and d are usable in the main() function as well as these can be also usable in the add() function.



Comments