3

This is in continuation with Strange behaviour of structures in C++ part 1

If I do this

#include<iostream>

using namespace std;

struct box
{
    //int simple_int;
    int arr[3];
};
int main()
{
    box a={10,20,30};
    //box b={100};
    //cout<<b.simple_int<<"\n";
    cout<<a.arr[0];
}

OUTPUT : 10 which is correct.

But if i remove the comments.

#include<iostream>

using namespace std;

struct box
{
    int simple_int;
    int arr[3];
};
int main()
{
    box a={10,20,30};
    box b={100};
    cout<<b.simple_int<<"\n";
    cout<<a.arr[0];
}

OUTPUT: 100 20 //instead of 100 10

Why?

Community
  • 1
  • 1
Naveen
  • 7,944
  • 12
  • 78
  • 165
  • It should be a={X, {10,20,30}} where X is whatever you want simple_int to be. I don't use this syntax often so I don't know why the first works, but with only an array it should be a={{10,20,30}} – Neil Kirk Jul 29 '13 at 14:25
  • It works because inner brackets are optional (see also Part 1 of this question, same answer) – MSalters Jul 29 '13 at 15:09

3 Answers3

10
box a = {10, 20, 30};

will initialize a as:

a.simple_int = 10;
a.arr = {20, 30, 0};

When you output a.arr[0], it will output 20, as expected.

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
3

Your code give the correct output.

Your struct will be initialized at :

a.simple_int = 10;
a.arr = {20, 30, 0};

So a.arr[0] will be 20.

Output of your program : 100 20 as expected.

If you want to avoid this kind of misunderstanding, initialize your structure more like :

box a = { 100, { 10, 20, 30 } };

With that, the result is :

a.simple_int == 100;
a.arr[0] == 10;
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
0

You can not initialize arrays like that. In the second example, your struct has an int and an array of ints. Your initialization of a doesn't correspond to anything and so the compiler partially fills it for you.

You could write a = {5, {10, 20, 30}} to make a.simple_int be 5 and make a.arr be an array of those 3 values.

DUman
  • 2,560
  • 13
  • 16