Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C Global And Local Variables

C program is a block of statements that are enclosed within { }. Each block has its own scope and it decides which Variable to use that falls under its scope. In other words, two variables with the same name can exist in the same program if they are declared in different blocks.

The variables have two scopes that way – Global and Local.

Global Variables

When a variable is declared outside of the program then its scope widens and all block of code in the C program can use that variable.

A global variable declaration is similar to any other variable declaration except it is declared outside of the main program and usually placed on top of the main function.

Local Variables

The variables that are declared inside a block, cannot be used outside of the block. The scope of such a variable is local to the block itself. They are called Local Variables.

Since the local variables are native to the block of codes in C programs, they have a higher priority than the global variables.

For example,

#include ;
int sum = 10;
/* declaring and initializing a Global variable */
int main()
{
   {
       int sum = 100;
/* Declaring and initializing a Local variable with the same name */
       printf(" SUM = %dn", sum);
    }
    system("PAUSE");
    return 0;
}

The scope of the variable is local inside of the block and global outside of the main program. The variable sum inside and outside are different, they are not the same. The local variable sum value gets printed to the output console because it has higher priority.

Output

Output – Global and Local Variable

References

  • Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,
  • Brian W. Kernighan, Dennis M. Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall.
Previous
Next

The post C Global And Local Variables appeared first on Notesformsc.



This post first appeared on Notesformsc, please read the originial post: here

Share the post

C Global And Local Variables

×

Subscribe to Notesformsc

Get updates delivered right to your inbox!

Thank you for your subscription

×