hanugm
hanugm

Reputation: 1387

Why no error on multiple declarations of same structure variable

I started doing programs on structures. I am confused about declaring structures itself because of the reason that it is allowing multiple declarations of same variable, which is not common in c.

Let us consider the following code:

#include<stdio.h>

struct {
        int x;
        int y;
}u, v;

int main()
{
        struct {int x; int y;} u = {3, 4},  v = {5, 6};
/*      struct {int x; int y;} u, v*/
        printf("%d\n", u.x);
        printf("%d\n", v.y);

        return 0;
}

In general, C disallows multiple declaration of same variable, here also it does if I don't comment out the second statement in main. But my doubt is that why it is neglecting multiple declaration of same variables if one is inside main and not other?

Upvotes: 1

Views: 78

Answers (2)

haccks
haccks

Reputation: 106012

C allows multiple declaration of same variable if they are declared in different scope. u declared in main, having block scope, will hide the declaration of u declared globally.

§6.2.1 (p4):

[...] 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: 2

user2371524
user2371524

Reputation:

Variables in some scope are allowed to shadow variables in an enclosing scope. So both variables exist, but if you write u inside main, it refers to the one declared in main.

Don't write such code, it's confusing, although legal.

Upvotes: 3

Related Questions