Jay He
Jay He

Reputation: 3

C++ aggregate initialiser behaviour with data array

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

Upvotes: 0

Views: 110

Answers (1)

Bob__
Bob__

Reputation: 12779

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.

Upvotes: 1

Related Questions