This short example comes from a real problem I had when accidently putting an old version of a header file into my include path. I wonder why the following code produces no warning or error with neither gcc nor visual studio:
main.cpp:
#include <stdio.h>
struct B {
int x;
};
extern void callB(B& b);
int main() {
B b;
b.x = 2;
int sideEffect = 1;
callB(b);
printf("x=%d\n", b.x);
printf("sideEffect=%d\n", sideEffect);
return 0;
}
call.cpp:
#include <stdio.h>
struct B {
int y;
int x;
};
void callB(B& b) {
printf("x=%d y=%d\n", b.x, b.y);
b.x = 3;
b.y = 4;
printf("x=%d y=%d\n", b.x, b.y);
}
The output of this short program is:
x=1 y=2
x=3 y=4
x=4
sideEffect=3
So I have two conflicting definitions of the struct B, and to make things worse, the extra member y is put before x. Thus in call.cpp the value of y is that of x in main.cpp So I can completely understand why the output is as it is, but since this behaviour would irritate both the maintainer of main.cpp and the other maintainer of call.cpp, I wonder why there is no check in the compiler or linker for this?
BTW: if you look into this with a debugger things become even more obscure, as the debugger assumes one of both definitions and may lead you into even more confusion (especially when the structs are more complex than here).