No error from multiple definitions of global variables

I was reading this thread (which discusses how you can't declare global variables in header files, etc) and thought I'd try it out. I seem to remember reading something about how const global variables in C++ were automatically static, that is, limited to the scope of one file, which would explain Elysia's last post.

Evidently I remembered correctly on that point.

Anyway. I came across a very strange phenomenon in my experimenting, which I eventually narrowed down to this:

"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell

A declaration of an identifier for an object that has file scope without an initializer, and
without a storage-class specifier or with the storage-class specifier static, constitutes a
tentative definition. If a translation unit contains one or more tentative definitions for an
identifier, and the translation unit contains no external definition for that identifier, then
the behavior is exactly as if the translation unit contains a file scope declaration of that
identifier, with the composite type as of the end of the translation unit, with an initializer
equal to 0.

So there you go: as long as things are global, no storage is necessarily set aside unless explicitly initialized. You can even do this:

Code:

int x;
int x;
int x;
int main() {
return 0;
}

Edit: And just for citizen, I compiled that with gcc -Wall -ansi -pedantic.

Yes, I was aware that you could declare global variables several times in one file, but I didn't think it applied to different source files. It looks like I was wrong.

Edit: And just for citizen, I compiled that with gcc -Wall -ansi -pedantic.

So did I, but just forgot to mention it.

dwk

Seek and ye shall find. quaere et invenies.

"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell