-1

Consider this:

#include <stdio.h>

static int b;

int main()
{
    {
        int b;

        {
            extern int b;

            b = 2;
        }
    }

    printf("%d", b);
}

Here by definition the identifier 'b' which is assigned the value 2 must have be the one with external linkage. However for some reason the 'clang' C compiler doesn't complain and the output of this code is '2'.

I'm assuming this because of $6.2.2.4 point in the C standard:

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

And as the previous visible declaration specifies no linkage ('int b').

Anyhow how can I make the declaration before the assignment to refer to the identifier with internal linkage (instead of the one with external such).

Edit: I see that this example is UB but this doesn't change my question.

AnArrayOfFunctions
  • 3,452
  • 2
  • 29
  • 66

1 Answers1

1

Your program has undefined behaviour. You can't have an identifier with both internal and external linkage at the same scope.

C11, §6.2.3, 4 says

If, within a translation unit, the same identfier appears with both internal and external linkage, the behavior is undefined.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • So how can it not be one? – AnArrayOfFunctions Jan 24 '16 at 01:52
  • They *can't* be one. Having both internal *and* external linkage for the same identifier doesn't make sense (standard says it's undefined). `int b;`(within the outer block inside `main()`) has no linkage. `extern int b;` declares `b` with external linkage which conflicts with `static int b;` which specifies internal linkage. – P.P Jan 24 '16 at 01:56
  • No I meant how can my example program doesn't produce UB without removing the variable without linkage. You are not answering my question. – AnArrayOfFunctions Jan 24 '16 at 02:02
  • Can you elaborate this "No I meant how can my example program doesn't produce UB without removing the variable without linkage"? – P.P Jan 24 '16 at 02:05
  • Just answer my question in the OP. – AnArrayOfFunctions Jan 24 '16 at 02:08
  • I am not sure what problem you are trying to solve. One way to access the varaible with internal linkage is to use a pointer to it: `static int b; int *p = &b;` and then use `p` to read/write the variable with internal linkage. With this, you can have another `b` with *no linkage*. Other than that I don't see any way to access the `static int b;` in the way you want. – P.P Jan 24 '16 at 02:11