Rjt Rjt - 1 year ago 88
C Question

Why is there no re-declaration error in this code?

#include <stdio.h>

int x=3;
int main()
int x=4;

return 0;

As we know a local declaration acts as a global declaration too. Since
has been already globally declared as 3, won't a new global declaration (non-tentative) cause a re-declaration error since 'merging' of more than one non-tentative definitions don't happen in case of local declarations ?

Answer Source

Nopes, here comes the scope.

The x inside main() has block scope and overrides (shadows) the global x inside the main().

Related, quoting C11, chapter ยง6.2.1, "Scopes of identifiers", (emphasis mine)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download