Category: 09. Scope Rules

https://cdn3d.iconscout.com/3d/premium/thumb/performance-review-3d-icon-png-download-11724991.png

  • Global Variables

    Global Variables

    In C programming language, the global variables are those variables that are defined outside all functions, usually at the top of a program. Global variables hold their values throughout the lifetime of a program, and they can be accessed inside any of the functions defined for the program.

    If a function accesses and modifies the value of a global variable, then the updated value is available for other function calls.

    If a variable is defined in a certain file, then you can still access it inside another code module as a global variable by using the extern keyword. The extern keyword can also be used to access a global variable instead of a local variable of the same name.

    Declaring Global Variable

    The declaration of a global variable in C is similar to the declaration of the normal (local) variables but global variables are declared outside of the functions.

    Syntax

    Consider the following syntax to declare a global variable:

    data_type variable_name;// main or any functionintmain(){}

    Example of Global Variable in C

    The following program shows how global variables are used in a program:

    #include <stdio.h>/* global variable declaration */int g =10;intmain(){/* local variable declaration */int a;/* actual initialization */
       a = g *2;printf("Value of a = %d, and g = %d\n", a, g);return0;}

    Output

    When you run this code, it will produce the following output −

    Value of a = 20, and g = 10
    

    Accessing Global Variables

    Global variables are accessible in all the functions in a C program. If any function updates the value of a global variable, then its updated value will subsequently be available for all the other functions.

    Example

    The following example demonstrates the example of accessing global variables in C language:

    #include <stdio.h>/* global variable declaration */int g =10;intfunction1();intfunction2();intmain(){printf("Value of Global variable g = %d\n", g);function1();printf("Updated value of Global variable g = %d\n", g);function2();printf("Updated value of Global variable g = %d\n", g);return0;}intfunction1(){
       g = g +10;printf("New value of g in function1(): %d\n", g);return0;}intfunction2(){printf("The value of g in function2(): %d\n", g);
       g = g +10;return0;}

    Run the code and check its output −

    Value of Global variable g = 10
    New value of g in function1(): 20
    Updated value of Global variable g = 20
    The value of g in function2(): 20
    Updated value of Global variable g = 30
    

    Scope and Accessibility of Global Variables

    Global variables are available to only those functions that are defined after their declaration. Global variables are declared outside of any function, so they can be accessed by all functions within the same file by default.

    Example

    In this example, we declared a global variable (x) before the main() function. There is another global variable y that is declared after the main() function but before function1(). In such a case, the variable y, even thought it is a global variable, is not available for use in the main() function, as it is declared afterwards. As a result, you get an error.

    #include <stdio.h>/* global variable declaration */int x =10;intfunction1();intmain(){printf("value of Global variable x= %d y=%d\n", x, y);function1();return0;}int y =20;intfunction1(){printf("Value of Global variable x = %d y = %d\n", x, y);}

    When you run this code, it will produce an error −

    Line no 11: error: 'y' undeclared (first use in this function)
       11 | printf ("Value of Global variable x = %d y = %d\n", x, y);
    
      |                                                     ^

    Accessing Global Variables With extern Keyword

    If you want to access a global variable when a local variable with same name is also there in the program, then you should use the extern keyword.

    Example

    In this C Program, we have a global variable and a local variable with the same name (x). Now, let’s see how we can use the keyword “extern” to avoid confusion −

    #include <stdio.h>// Global variable xint x =50;intmain(){// Local variable xint x =10;{externint x;printf("Value of global x is %d\n", x);}printf("Value of local x is %d\n", x);return0;}

    Output

    When you run this code, it will produce the following output −

    Value of global x is 50
    Value of local x is 10
    

    Avoid Using Global Variables

    Global variables can simplify the programming logic. They can be accessed across functions, and you need not use a parameter-passing technique to pass variables from one function to another. However, it is not wise or efficient to have too many global variables in a C program, as the memory occupied by these variables is not released till the end of the program.

    Using global declaration is not considered a good programming practice because it doesn’t implement a structured approach. Global declarations are also not advised from a security point of view, as they are accessible to all the functions. Finally, using global declarations can make a program difficult to debug, maintain, and scale up.

  • Static Variables

    By default, a C variable is classified as an auto storage type. A static variable is useful when you want to preserve a certain value between calls to different functions. Static variables are also used to store data that should be shared between multiple functions.

    Static Variables

    The static variables belong to the static storage class, they are initialized only once and preserve the values till the end of the program, The static keyword is used to declare the static variables.

    Features of Static Variables

    The following are some of the features of static variables in C programming language −

    • The compiler allocates space to a static variable in the computers main memory.
    • Unlike auto, a static variable is initialized to zero and not garbage.
    • A static variable is not re-initialized on every function call, if it is declared inside a function.
    • A static variable has local scope.

    Declare a Static Variable

    To declare a static variable in C language, use the static keyword and assign the initial value. Following is the syntax to declare a static variable:

    static datatype var = value;

    Here,

    • datatype represents the type of variable like int, char, float, etc.
    • var is the name of variable given by user.
    • value is any value given to initialize the variable. By default, it is zero.

    Examples of Static Variables in C

    Example: Using Static Variable

    Here is an example of how you can use a static variable in C language −

    #include <stdio.h>intmain(){autoint a =-28;staticint b =8;printf("The value of auto variable: %d\n", a);printf("The value of static variable b: %d\n",b);if(a !=0)printf("The sum of static variable and auto variable: %d\n",(b+a));return0;}

    Output

    When you run this code, it will produce the following output −

    The value of auto variable: -28
    The value of static variable b: 8
    The sum of static variable and auto variable: -20
    

    Example: Create Counter Function W/O Using Static Variable

    In this example, x is an auto variable by default and initialized to 0 every time when the counter() function is called. On each subsequent call, it gets re-initialized.

    #include <stdio.h>intcounter();intmain(){counter();counter();counter();return0;}intcounter(){int x;printf("Value of x as it enters the function: %d\n", x);
       x++;printf("Incremented value of x: %d\n", x);}

    Output

    Run the code and check its output −

    Value of x as it enters the function: 0
    Incremented value of x: 1
    Value of x as it enters the function: 0
    Incremented value of x: 1
    Value of x as it enters the function: 0
    Incremented value of x: 1
    

    However, when the variable x in the counter() function is declared as static, it is initialized to “0” when the counter() function is called for the first time. On each subsequent call, it is not re-initialized. Instead, it retains the earlier value.

    Example: Create Counter Using Static Variable

    Change the declaration of “x” to “static int x = 0;” and run the program again −

    #include <stdio.h>intcounter();intmain(){counter();counter();counter();return0;}intcounter(){staticint x =0;printf("Value of x as it enters the function: %d\n", x);
       x++;printf("Incremented value of x: %d\n", x);}

    Output

    Now, when you run this code, it will produce the following output −

    Value of x as it enters the function: 0
    Incremented value of x: 1
    Value of x as it enters the function: 1
    Incremented value of x: 2
    Value of x as it enters the function: 2
    Incremented value of x: 3
    

    Passing Static Variable to Function

    You can pass a static variable to a function. However, a formal parameter cannot be declared as static, as C uses the function parameters as local auto variables inside a function.

    Example

    In this code, we pass a static variable to a function. However, the change in its value is not reflected in the calling function.

    #include <stdio.h>intmyfunction(int x);intmain(){staticint x =5;myfunction(x);printf("in main - x:%d\n", x);return0;}intmyfunction(int x){
       x++;printf("Incremented value of x: %d\n", x);}

    Output

    Run the coce and check its output −

    Incremented value of x: 6
    in main - x:5
    

    Similarities Between Static and Global Variables

    A static variable has certain similarities with a global variable. Both of them, if not explicitly initialized, both are initialized to “0” (for numeric types) or “null pointers” (for pointers).

    The scope of a static variable is restricted to the function or the block in which it is declared. This is unlike a global variable, which is accessible throughout the program. Also, a static variable can be imported in another code file, as we do by using the extern keyword.

    Example

    You can declare a global variable as static too. Take a look at the following example −

    #include <stdio.h>intmyfunction();staticint x =5;intmain(){myfunction(x);printf("Inside the main function, x: %d\n", x);return0;}intmyfunction(){
       x++;printf("Incremented value of x: %d\n", x);}

    Output

    When you run this code, it will produce the following output −

    Incremented value of x: 6
    Inside the main function, x: 6
    

    It is better to use static variables to be accessible only within a file. On the other hand, use global (with extern) variables to be accessible from anywhere in a program (if declared extern in other files).

  • Scope Rules

    A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in C programming language −

    • Inside a function or a block which is called local variables.
    • Outside of all functions which is called global variables.
    • In the definition of function parameters which are called formal parameters.

    Let us understand what are local and global variables, and formal parameters.

    Local Variables

    Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own.

    Example

    The following example shows how local variables are used. Here all the variables a, b, and c are local to main() function.

    #include <stdio.h>intmain(){/* local variable declaration */int a, b;int c;/* actual initialization */
      a =10;
      b =20;
      c = a + b;printf("value of a = %d, b = %d and c = %d\n", a, b, c);return0;}

    Global Variables

    Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.

    A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.

    Example

    The following program show how global variables are used in a program.

    #include <stdio.h>/* global variable declaration */int g;intmain(){/* local variable declaration */int a, b;/* actual initialization */
      a =10;
      b =20;
      g = a + b;printf("value of a = %d, b = %d and g = %d\n", a, b, g);return0;}

    A program can have same name for local and global variables but the value of local variable inside a function will take preference. Here is an example −

    Example

    #include <stdio.h>/* global variable declaration */int g =20;intmain(){/* local variable declaration */int g =10;printf("value of g = %d\n",  g);return0;}

    When the above code is compiled and executed, it produces the following result −

    value of g = 10
    

    Formal Parameters

    Formal parameters, are treated as local variables with-in a function and they take precedence over global variables. Following is an example −

    Example

    #include <stdio.h>/* global variable declaration */int a =20;intmain(){/* local variable declaration in main function */int a =10;int b =20;int c =0;printf("value of a in main() = %d\n",  a);
      c =sum( a, b);printf("value of c in main() = %d\n",  c);return0;}/* function to add two integers */intsum(int a,int b){printf("value of a in sum() = %d\n",  a);printf("value of b in sum() = %d\n",  b);return a + b;}

    When the above code is compiled and executed, it produces the following result −

    value of a in main() = 10
    value of a in sum() = 10
    value of b in sum() = 20
    value of c in main() = 30
    

    Initializing Local and Global Variables

    When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −

    Data TypeInitial Default Value
    int0
    char‘\0’
    float0
    double0
    pointerNULL

    It is a good programming practice to initialize variables properly, otherwise your program may produce unexpected results, because uninitialized variables will take some garbage value already available at their memory location.