cstaticglobal

Why I didnot get Multiple definition Error?


#include <stdio.h>

#define MAX 5
 
static int data = 10; 
int increment(void *);

int increment(void *ptr)
{
    int *p = ptr;
    static int data =15;
    for (int loop=0; loop < MAX; loop++)
    {
        data++;
    }
    return data;
}
 
int main(void)
{
    printf("%d\n", data++);
    static int data = 25;
    for (int loop=0; loop < MAX ; loop++)
    {
        data++;
    }
    printf("%d\n", data++);
    data = increment(&data);
    printf("%d\n", data++);
    return 1;
}

I understand that, static remains in memory till the end of the program ends. Then in above code there is a global static int data and same static int data in main. In Increment function, I understand that it has a local scope.

According to me it should give multiple definition error. But it didnt given. Why? How program identifies that here I have to take global data and here I have to take it main data?


Solution

  • From C17, 6.2.1 (Scope of identifiers), paragraph 4:

    … 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.

    OP's code has three different static int data variables with different scopes.

    The use of data within the main function before the local declaration of static int data denotes the global data variable with file scope. Other uses of data within the main function after the local declaration of static int data denote the local data variable with block scope.