Wayne
Wayne

Reputation: 63

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

#include <stdio.h>

int x=3;
int main()
{
  int x=4;
  printf("%d",x);

  return 0;
}

As we know a local declaration acts as a global declaration too. Since x 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 ?

Upvotes: 1

Views: 70

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134386

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.

Upvotes: 4

haccks
haccks

Reputation: 106102

As we know a local declaration acts as a global declaration

No. that's wrong.

Global x is not visible to main in the presence of local x. Compiler will not generate any warning or error as its allowed by C standard. Scope of the the variables are different. x outside the main has global scope while x inside the main has function scope.

Upvotes: 2

Related Questions