Tudor Ciotlos
Tudor Ciotlos

Reputation: 1845

How do global and static variables work together in C?

I have to determine the output of this program (without running it on the computer). I am pretty unsure on how the global and static variables work together.

#include <stdio.h>

void f(int d);

int a = 1, b = 2, c = 3, d = 4;

int main()
{
    int a = 5, c = 6;
    f(a);
    f(b);
    f(c);
    printf("%d %d %d %d\n",a,b,c,d);
    return 0;
}

void f(int d)
{
    static int a = 0;
    a = a + 7;
    b = a + d;
    c++;
    d--;
    printf("%d %d %d %d\n",a,b,c,d);
}

Upvotes: 2

Views: 551

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 476940

The nearest visible binding in scope hides all the further ones. So in main all the names refer to the local variables, and in f only a is the local one (albeit static, that's immaterial), d refers to the function parameter, and b and c refer to the global ones.

You can unhide farther-away names to a limited extend with the extern keyword, but given enough local scopes you can always create and hide variables that you can never see from somewhere deeper.

Upvotes: 1

md5
md5

Reputation: 23699

If two variables are declared with the same identifier, the accesses refer to the one with the smallest scope.

C11 (n1570), § 6.2.1 Scopes of identifiers

If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will end strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

Local variable defintions always "hide" global variables with the same name. An inner scope always takes precedence over an outer one. Some compilers also produce warning when a variable "shadows" another one.

Upvotes: 1

Related Questions