Learn how to write the C program step-by-step | Lesson - 7

 Storage Classes

C Program


TOPIC

  • External Variables
  • Static Variables
  • Register Variables

Basics of C language
C Program
External Variables

  • External variables are not confined to a single function. Their scope extends to two or more functions or may be an entire program.
  • External variables are recognized globally, they can be accessed from any function that falls within their scope. They retain their assigned values within this scope.
  • External variable can be assigned a value within one function, and this value can be used (accessed) within another function.
 
Program: Generate Multiplication Table of any given number. Using External Variable.

Program-1

#include<stdio.h>
/* Generate Multiplication Table of any given number. Using External Variable */
int p = 0;
void main ()
      
{      int i;
        printf("\nThis Program generates a Table");
        printf("\nEnter the Number : ");
        scanf("%d",&p);
        printf("\n\t\tThe Multiplication Table for :   %d\n",p);
        printf("\n\t\t-------------------------------\n");
        for (i = 1; i<=10; i++) 
        printf("\n\t\t\t %d * %2d = %3d \n", p,i,i*p);
        }

  • External variables can be used for transferring information back and forth between functions. We can transfer information into a function without using arguments, which can be very helpful when a function requires numerous input data items. Since the return statement can return only one data item, now we have a way to transfer multiple data items out of a function.
  • An external variables definition is written in the same manner as an ordinary variable declaration. It must appear outside of, and usually before, the functions that access the external variables. The assignment of initial values can be included within an external variable definition.
 
Program : Calculate area of a rectangle. Using a global variable

Program-2

#include<stdio.h>
/* Calculate area of a rectangle. Using a global variable */
int length, width, area;
void main ()      
{      printf("Enter the length of a rectangle : ");
        length = get_int( );
        printf("Enter the width : ");
        width = get_int( );
        calc( );
        printf("\nThe area is %d,\n",area);
        return;
        }
get_int( )
{        int numb;      
          scanf("%d",&numb);
          return(numb);
          }
 
calc( )
{        area = length * width ;
          return;  
         } 
 
  • An external variable definition will automatically allocate the required storage space in computer's memory for the external variables.
  • The storage-class specifier extern is not required in an external variable definition, since the external variables will be identified by the location of their definition within the program.
  • If a function requires an external variable that has been defined earlier in the program, then the function many access the external variable freely, without any special declaration within the function.
  • If the function definition precedes the external variable definition, then the function must include a declaration for that external variable. The function definitions within a large program often include external variable declarations, whether they are needed or not, as a matter of good programming practice.

Program: Calculate Average Length of Several Lines

Program-3

#include<stdio.h>
/* Calculate Average Length of Several Lines. Using external variables. */
int total=0 lines=0;
void main ()      
{      
        int n; 
        float average;
        int linecount( );
        printf("\nEnter few lines below (Blank line to terminate)\n");
        while ((n = linecount( )) > 0)
        {
            total += n;
            ++lines;
        }
average = (float) total/lines;
printf("Average number of characters per line: %5.2f\n", average);
{        
 int linecount( );         
{         
    char line[80];
    int counter = 0;  
    while ((line[counter] = getchar( )) !='\n')
                ++counter;

          return(counter);  
         }

 

  • Total and lines are external variables representing the total number of characters read and the total number of lines, respectively. Both of these variables are assigned initial values of zero. These values are successively modified within main, as additional lines of text are read.   
  • An external variable declaration must begin with the storage-class specifier extern. The name of the external variables and its data type must agree with the corresponding external variable definition that appears outside of the function.
  • Storage space for external variable will not be allocated as a result of an external variable declaration.
  • An external variable declaration cannot include the assignment of initial values.    
  • There are inherent dangers in the use of external variables, since an alteration in the value of an external variable within a function will be carried over into other parts of the program. Thus, there is the possibility that the value of an external value will be changed unexpectedly, resulting in a subtle programming error.    

Static Variables

  • Static variables are defined within individual functions and therefore have the same scope as automatic variables, i.e.., they are local to the functions in which they are defined.
  • Static variables retain their values throughtout the life of the program. So, if a function is exited and then re-entered later, the static variable defined within that function will retain their former values. This feature allows functions to retain information permanently throughout the execution of a program.
  • Static variables are defined within a function in the same manner as automatic variables, except that the variable declaration must begin with the static storage-class designation.
  • Static variables can be utilized within the function in the same manner as other variables. But they cannot be accessed outside of their defining function.

 

Program: Difference between Static & Automatic Variables

 

Program-1A

#include<stdio.h>
/* Difference between Static & Automatic Variables */

void main ()
      
{      increment( );
        increment( );
        increment( ); 
        increment( ); 
        }

increment( )
 
{       char alphabet = 65;
         printf("\n The Character Stored in 'Alphabet' : %c", alphabet++);
         return;
        }

Program-1B

#include<stdio.h>
/* Difference between Static & Automatic Variables */

void main ()
      
{      increment( );
        increment( );
        increment( ); 
        increment( ); 
        }

increment( )
 
{       static char alphabet = 65;
         printf("\n The Character Stored in 'Alphabet' : %c", alphabet++);
         return;
        }

  • In the case of automatic or static variable having the same names as external variables, the local variables will take precedence over the external variables, though the values of the external variables will be unaffected by any manipulation of the local variables. Thus, the external variables maintain their independence with locally defined automatic and static variables. The same is true of local variables within one function that have the same names as local variables within another function.
  • Initial values can be included in static variable declarations. The rules associated with the assignment of these values are same as the rules associated with the initialization of external variables, such as:
  • The initial values must be expressed as constants, not expressions.
  • The initial values are assigned to their respective variables at the beginning of program execution. The variables retain these values throughout the life of the program, unless different values are assigned during the course of the computation.
  • Zeros will be assigned to all static variables whose declarations do not include explicit initial values. Thus, static variables will always have assigned values.

 

 

Register Variables 

  • Store the variable being declared in a CPU register.
  • The register type modifier tells the compiler to store the variable being declared in a CPU register, to optimize access.
  • Most computers have some internal registers. Operations can be performed upon the data stored in registers more quickly than upon the data stored in memory.
  • The scope and initialization of the register variables is the same as for the automatic variables, except for the location of storage. Thus, the register variables are local to a function and they come into existence, when the function is invoked and the value will be lost once the functions is exited.
  • If you use register, remember that the number of registers available is limited. Try to determine which variables in your program are used most often, then declare them as register variables.
 

Program-1

#include<stdio.h>
/* program using Register Variables */
void main ()
      
{      register int i;
        int number, digit, sum;
        printf("\nSum Of Cubes Of Digits is Equal To The Number Itself Are : "); 
        for( i =1;  i <=999;i++)
        {        sum = 0;
                  number = i;
                  while(number)
                 {     digit = number%10;
                        number = number/10;
                        sum = sum + digit * digit * digit;
                        }
         if(sum == i) printf("\n %d" ,i);
       

If you find this article informative, please share the post to your friends. 
 
 
 

Exercise regularly. Eat a nutritious diet. Don't smoke - WHO (Covid-19).

See also:

Click here to read ..

 
 

Thanks a lot for reading!
जय हिन्द ! वन्दे मातरम् !!
Neel Kamal

Learn how to write the C program step-by-step | Lesson - 7 Learn how to write the C program step-by-step | Lesson - 7 Reviewed by Neel Kamal on December 28, 2020 Rating: 5

No comments:

For More Details Subscribe & Comment..!

Powered by Blogger.