Assessment of expression in the task

I was just surprised to see that in GCC (4.3.2) the left side of the assignment expression can be evaluated before the right side:

int x,y; int& getX() { std::cout << "getX\n"; return x; } int& getY() { std::cout << "getY\n"; return y; } void test() { x = 3; y= 4; getX() = getY(); } 

Call test () outputs

 getX getY 

While MSVC uses the opposite order. Is there any definition for this standard?

+4
source share
4 answers

Yes and no.

In essence, the standard determines that it is not specified, and only guarantees that the arguments will be ready when the function is called.

EDIT: Even worse, evaluating expressions may alternate. See an example.

Basically, you should just remember that whenever you have a function, and a = b is a function call: operator=(a , b) , then the order in which the arguments of the functions are evaluated is not specified.

GCC usually goes from right to left, but the optimizer may decide that sometimes left to right is faster, for example. This may even change at runtime, although for practical reasons I have never seen such an implementation.

EDIT:

Since the Standard does not promise concrete ordering or even atomic performance, the following statement:

 test(foo() + bar(), fud()); 

May result in 4 of the following call sequences:

  • foo, bar, fud
  • bar, foo, fud
  • fud, foo, bar
  • fud, bar, foo

which are more or less "expected" when you understand the "undefined" term and its consequences ... but it can also lead to the following two sequences:

  • foo, fud, bar
  • bar, fud, foo

which is much more surprising. This is an alternation.

I left the + operation here, which can be performed only once, when foo and bar were calculated, but can be performed before or after fud .

If functions are pure or have completely disjoint sets of operations, it does not matter. Sometimes there are some additional side effects, and this can even lead to memory leaks ...

+5
source

The standard leaves the evaluation order unspecified, which means that the implementation can choose any desired order.

+2
source

The assignment operator = does not coolly introduce a sequence point in C ++ 98/03 or in C ++ 11 the expressions on both sides are not affected by the sequence relative to each other.

+2
source

The procedure for evaluating operator operands = not defined in accordance with the specification:

Except where noted, the procedure for evaluating the operands of individual operators and subexpressions of individual expressions and the order in which side effects occur are not defined

+2
source

Source: https://habr.com/ru/post/1384921/


All Articles