Global Variable - Devbhoomi

FREE JOB ALERT & ONLINE TUTORIALS

Hot

Post Top Ad

Sunday 5 November 2017

Global Variable

Global variables in c have their declaration outside the function definition of all functions used within the program.

Example :

    #include <stdio.h>

    /* global variable declaration */
    int z;
    int main ()
    {
    /* local variable declaration */
    int x, y;

    /* actual initialization */
    x = 10;
    y = 20;
    z = x + y;

    printf ("Value of x = %d, y = %d and z = %d\n", x, y, z);
    return 0;
    }

Output :
Value of x = 10, y = 20 and z = 30

Explanation :
The variable z is a global variable, and it can be accessed by any function.

Example :

    #include <stdio.h>

    /* global variable declaration */
    int a = 20;

    int main ()
    {
    /* local variable declaration */
    int a = 10;
    printf ("Value of a = %d\n", a);
    return 0;
    }

Output :
Value of a = 10

Explanation :
Variable a is locally as well as globally defined, but the local variable value will be preferred.

NOTE :
  • If the local and global variable have same name then value of local variable will take preference.

No comments:

Post a Comment

Post Top Ad