Site icon TestingDocs.com

C Global Variables

Overview

Global variables are variables defined outside of all the functions in the program. The global variable declarations are usually done at the beginning of the program but after the preprocessor directives. The lifetime of the global variables would be throughout the entire program.

Example

The following example demonstrates the use of the global and local variables
in a C program:

 

/**
*************************************************
 * Program Description:
 * C Local Variable Demo
 * Filename: global.c
 * C Tutorials - www.TestingDocs.com
 ************************************************
 */
#include
/* Global variable declaration */
int global_number = 10;

/* Function prototype */
void demo_function();

int main()
{
    /* local variable */
    int local_number = 20;

    printf(" The local variable is = %d \n",local_number);
    printf(" The global variable in [main()] is = %d \n",global_number);

    demo_function(); // function call
    return 0;
}

/* Global variable is accessible in the function */
void demo_function()
{
    /* local variable in function*/
    int local_fun_number = 30;

    printf(" The local function variable is = %d \n",local_fun_number);
    printf(" The global variable in [demo_function()] is = %d \n",global_number);

}

 

We can see that the global variable can be accessed by the function. Unlike a local variable, a global variable is available for use throughout the entire program.

C Tutorials

C Programming Tutorials on this website:

https://www.testingdocs.com/c-language-tutorial/

Exit mobile version