-2

I created a struct:

struct number_struct
{
    int i;
    float f;
} struct_a;

Thus struct_a is of type number_struct.

Later in int main I write:

number_struct struct_a = { 0 };
number_struct struct_b = { 0 };

The confusion is that since I have declared struct_a twice, I would expect a message from visual studio saying that it has been declared twice, aka name collision. Why does this not occur? It does occur if I declare struct_b twice but within the main routine.

Besides this, if I do the following without initializing the structs:

std::cout << struct_a.i << "\t" << struct_b.i << std::endl;
std::cout << struct_a.f << "\t" << struct_b.f << std::endl;

I get a runtime error saying that the sturct is being used without initialization. Why does the compiler not initialize the struct (and standard type variables) to 0 automatically?

quantum231
  • 2,420
  • 3
  • 31
  • 53

1 Answers1

0
struct number_struct {
    int i;
    float f;
} struct_a;

creates an instance of number_struct in the global scope. Then, you create an instance of number_struct in main, which hides the instance created in the global scope. To access the instance in the global scope, use the scope-resolution operator, ::struct_a.

As to the runtime error, what version are you compiling with? The standard says to initialize global variables to 0 (not that you shouldn't explicitly initialize yourself).

Max
  • 51
  • 1
  • 6
  • if I type static int i; and then do cout << i; it works. However, just using int i and cout << i causes runtime error saying i not initialized. It works if I do int i(0); cout << i. – quantum231 Jul 07 '16 at 00:27
  • I am using the visual studio 2013 version 12.0.31101.00 update 4 – quantum231 Jul 07 '16 at 00:27
  • Have you tried compiling with gcc? If not, I suggest upgrading to v14 (https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx). Its free, by the way. The only reason I say this is that for a while Microsoft's compilers were not at their best. – Max Jul 07 '16 at 00:33
  • Can you clarify what you mean by not initializing the structs? My above comment I thought that you were talking about global variables. – Max Jul 07 '16 at 00:38
  • OK. I am taking about struct created inside int main() like this: number_struct struct_x; number_struct struct_y; and not initializing them by using {0} or something. – quantum231 Jul 07 '16 at 08:28