Why does the program output 01 instead of 00?
#include <iostream> namespace A { extern "C" int x = 0; }; namespace B { extern "C" int x; }; int main() { std::cout << B::x; A::x = 1; std::cout << B::x; } The program displays 01 because it should output 01 . Language specification clearly speaks
If you’re referring to the namespace scopes, you’ll refer to the same variable.
Two variable declarations with C-linking with the same name (ignoring the qualifying namespace names), which are located in different namespaces, refer to the same variable.
Both declarations - A::x and B::x - declare the same variable.
The question itself is somewhat surprising. Under what circumstances can this be expected from such an output program 00 ? If A::x and B::x declare different variables? But then the program would not compile at all due to the lack of definition for B::x .
extern "C" spoils everything :) - in fact, you declare a single variable x in two namespaces, which, being extern "C" , knows nothing about namespaces ...
Try to define the second variable - well, type
namespace B { extern "C" int x = 3; }; and you will receive the appropriate messages when compiling.
Source: https://ru.stackoverflow.com/questions/913802/
All Articles
00? Where is the rationale for the expected behavior? Without it, your question sounds like "why in the program 2 + 2 is 4, not 5". - AnT