Evaluation order of initializer list parameters

J

Juha Nieminen

IIRC for example when calling a function taking several parameters,
the order in which those parameters will be evaluated is not specified
by the standard. (In other words, if you write "f(a, b)" then b might
be evaluated before a.) This means that if I do this:

f(func1(), func2());

it's not guaranteed that func1() will be called first and func2() after
that. It may happen the other way around.

Is this also so with initializer lists? For example, if I initialize
a struct like this:

SomeStruct obj = { func1(), func2() };

is it guaranteed that func1() will be called first, and then func2()?
(I know that the elements of the struct will be initialized in order.
However, are the parameters to those elements also evaluated in that
same order?)

Likewise for an array:

int anArray[] = { func1(), func2() };

is it guaranteed that func1() will be called first, and then func2()?
(Also here the array elements are initialized in order, but does that
mean that the parameters are evaluated in the same order?)

How about C++11 initializer lists? Such as:

std::vector<int> aVector = { func1(), func2() };
 
V

Victor Bazarov

IIRC for example when calling a function taking several parameters,
the order in which those parameters will be evaluated is not specified
by the standard.[..]

Is this also so with initializer lists? [..]

Yes. The evaluation order is not explicitly specified.

V
 
J

Johannes Schaub

Juha said:
IIRC for example when calling a function taking several parameters,
the order in which those parameters will be evaluated is not specified
by the standard. (In other words, if you write "f(a, b)" then b might
be evaluated before a.) This means that if I do this:

f(func1(), func2());

it's not guaranteed that func1() will be called first and func2() after
that. It may happen the other way around.

Is this also so with initializer lists? For example, if I initialize
a struct like this:

SomeStruct obj = { func1(), func2() };

No, the order is specified to be from left to right, and each evaluation of
an element is sequenced after the evaluation of the preceeding element.

That applies disregarding of the semantics of the initializer list. For
example

struct A {
A(int, int);
};

int f();
int g();

A a = { f(), g() };

In this example, first f is called, and then g, even though both of these
function calls are arguments of a call to a constructor of A.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top