According to the C Standard (6.2.1 Scopes of identifiers)
- ...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.
In your example the first declared identifier
int xyz = 10;
has file scope. The second declared identifier
int xyz = 20;//line 2
has block scope that is enclosed in the file scope. That is the block scope is an inner scope relative to the file scope. The second declared identifier hides the first declared identifier inside the block scope.
The same is valid for C++. Only C++ has namespaces and using a qualified name you can access a hidden variale. For example
#include <iostream>
int xyz = 10;
int main() {
int xyz = 20;//line 2
std::cout << "xyz = " << xyz << ", ::xyz = " << ::xyz << std::endl;
return 0;
}
Here ::
before xyz
denotes the global namespace.
Take into account that you could also use the same name for a function parameter declaration in a function declaration. For example
void f( int xyz );
In this case this identifier has function prototype scope. Also you could even to declare a lable with the same name as for example
In C
xyz:;
int xyz = 20;
or in C++
xyz:
int xyz = 20;
Also in C tags have its own namespace. So this declaration is valid in C
xyz:;
struct xyz
{
int xyz;
};
int xyz = 20;