Discussion: Global vs Local Variables with the Same Name

I have what I think is an interesting question. What would be the ouput of the following code?

globals.h:
 
int test = 0;


main.cpp:
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "globals.h"

int main()
{
	printf("global addr\t%p\tvalue\t%d\n", &test, test);
	int test = 1;
	printf("local addr\t%p\tvalue\t%d\n", &test, test);
}


The answer may be obvious but I think it's interesting anyway. I'm using visual studio's compiler at the moment.

Do all C++ compilers allow this code?

Does anyone have any insight on how some of the different compilers might treat this code?

I'm not posting the output (although I'm sure it's not surprising) just for the sake of discussion. I don't see a way to do spoilers or anything.
Do all C++ compilers allow this code?
Do you mean in actuality or in theory? In theory, any C++ compiler must accept the code, because a program that rejects it would not be a C++ compiler.
In actuality, there may exist lousy programs that are advertised as C++ compilers and reject that code, or generate incorrect code.

Does anyone have any insight on how some of the different compilers might treat this code?
I'm pretty sure the latest versions of the four main compilers (VC++, Clang, ICC, GCC) all behave correctly with regard to scope rules.
Topic archived. No new replies allowed.