0

When altering the order of data array, it seems like datais always the one got initialized by the aggregate initializer(not alter). Why?

struct SqList
{
   ElemType alter[MAXSIZE];
   ElemType data[MAXSIZE];//swap order here
   int Length;
};

Isn't the compiler shall treat the first valid memory block as an initializer target?

First of all, I have a SqList class and an overloaded operator<< to print the content.

struct SqList
{
    ElemType data[MAXSIZE];
    ElemType alter[MAXSIZE];
    int Length;
};

ostream& operator<<(ostream& os,const SqList& sql)
{
    for(auto i:sql.data)
        os<<i<<" ";
    os<<"\n";

     for(auto i:sql.alter)
        os<<i<<" ";
    os<<"\n";
    return os;
}

In main(), the instance of SqList is created with aggregate initializer

int main()
{
    SqList s{1,2,3,4,5};
    cout<<s;
}

It is interesting to see that whether if I swap the order of data and alter in SqList, data always got initialized with {1,2,3,4,5}

Here is the code if you are interested.

compiler explore

5
  • 1
    Since you're using C++ you really should be using std::vector and steer well away from fixed-length C arrays. Commented Mar 27, 2020 at 23:28
  • If you want control over where those values go, implement a constructor. You're asking a lot of C++ here to know what you want. Commented Mar 27, 2020 at 23:29
  • @tadman there is nothing wrong with using fixed arrays in C++. However, it is preferable to use std::array for them, instead of the older C syntax. Commented Mar 28, 2020 at 0:00
  • @RemyLebeau You say there's "nothing wrong" and yet all I see on Stack Overflow are cases of where people overflow the array, fail to initialize members properly, and otherwise mess up things that std::vector will do for you automatically. Commented Mar 28, 2020 at 0:02
  • Well, the original purpose of those lines was mean to be a post-reading practice of some data-structure textbook. Commented Mar 28, 2020 at 1:59

1 Answer 1

1

if I swap the order of data and alter in SqList, data always got initialized with {1,2,3,4,5}

No, that's not the observed behavior. See e.g those two versions: https://godbolt.org/z/VTeheX vs https://godbolt.org/z/bkA8zs

While you swap the lines in the class declaration, in the definition of the overload of operator<< your code always prints data before alter and the outputs (not to mention the warnings) of the two versions are different.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was expecting the result you have. But somehow I end with creating this question. And the warning goes away with this SqList s{{0,1,2,3,4,5},{1,2,3,4,5},5};

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.