Search code examples
cglobal-variablesansi-c

The external (global) variables in C


I'm reading a C programming book, The C Programming Language (K & R, 2nd Edition). I got to know the facts about external variables in the book, but I found something different when I practiced the principles by myself. The book says:

"... because external variables remain in existence permanently, rather than appearing and disappearing as functions are called and exited, they retain their values even after the functions that set them have returned."

However, when I code like this:

#include <stdio.h>

int i = 0;
void foo();

main()
{
    foo();                  
    printf("%d", i);
    return 0;
}

void foo()
{
    i = 1;
}

The program prints 1 instead of 0 which is the original value of the external variable i. So I wonder where I get mistakes while thinking about the principle and how to understand it.


Solution

  • ...they retain their values even after the functions that set them have returned.

    I'm guessing it's a question of interpretation on your part.

    Given that the variable is global, every time you change it, in any function, it will assume and retain that value until it is next modified.

    Take the function:

    int i = 0;
    void foo();
    
    int main()
    {
        int x = 0;
        foo(x);                  
        printf("%d", i);
        printf("%d", x);
        return 0;
    }
    
    void foo(int x)
    {
        x = 1;
        i = 1;
    }
    

    result: x = 0 i = 1

    x is passed by value, essentially, a copy of it, so as soon as the function goes out of scope, i.e. returns, the copy is discarded. i is global so you don't even need to pass it; every function is aware of its existence and will change its value.