Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function evaluation order in assignment operator

int& foo() {
   printf("Foo\n");
   static int a;
   return a;
}

int bar() {
   printf("Bar\n");
   return 1;
}

void main() {
   foo() = bar();
}

I am not sure which one should be evaluated first.

I have tried in VC that bar function is executed first. However, in compiler by g++ (FreeBSD), it gives out foo function evaluated first.

Much interesting question is derived from the above problem, suppose I have a dynamic array (std::vector)

std::vector<int> vec;

int foobar() {
   vec.resize( vec.size() + 1 );
   return vec.size();
}

void main() {
   vec.resize( 2 );
   vec[0] = foobar();
}

Based on previous result, the vc evaluates the foobar() and then perform the vector operator[]. It is no problem in such case. However, for gcc, since the vec[0] is being evaluated and foobar() function may lead to change the internal pointer of array. The vec[0] can be invalidated after executation of foobar().

Is it meant that we need to separate the code such that

void main() {
   vec.resize( 2 );
   int a = foobar();
   vec[0] = a;
}
like image 550
Yiu Fai Avatar asked Nov 28 '11 11:11

Yiu Fai


People also ask

What is the typical evaluation order for an assignment operator?

5.17 Assignment and compound assignment operators In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

What is the order of operand evaluation?

First, the left operand of * is evaluated; it produces the value 4. Then the right operand of * is evaluated. Since evaluation of the left operand set x to 4, evaluation of the right operand produces 4. Finally, the * operator itself is evaluated, producing the value 16.

Does C evaluate left-to-right?

There is no concept of left-to-right or right-to-left evaluation in C, which is not to be confused with left-to-right and right-to-left associativity of operators: the expression f1() + f2() + f3() is parsed as (f1() + f2()) + f3() due to left-to-right associativity of operator+, but the function call to f3 may be ...

What can be used to change the order of evaluation expression in C?

The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.


1 Answers

Order of evaluation would be unspecified in that case. Dont write such code

Similar example here

like image 167
Prasoon Saurav Avatar answered Sep 25 '22 19:09

Prasoon Saurav