Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression evaluation order

Tags:

c++

I recently got confused by the following c++ snippet:

#include <cstdio>

int lol(int *k){
  *k +=5;
   return *k;
}

int main(int argc, const char *argv[]){
  int k = 0;
  int w = k + lol(&k);
  printf("%d\n", w);
  return 0;
}

Take a look at line:

int w = k + lol(&k);

Until now I thought that this expression would be evaluated from left to right: take current value of k (which before calll to lol function is 0) and then add it to the result of lol function. But compiler proves me I'm wrong, the value of w is 10. Even if I switch places to make it

int w = lol(&k) + k;

the result would be still 10. What am I doing wrong?

Tomek

like image 296
tomuś Avatar asked Nov 24 '11 21:11

tomuś


People also ask

What is the correct order of evaluation of the expression in C?

C. D. Explanation: Simply called as BODMAS (Bracket of Division, Multiplication, Addition and Subtraction).

What are the rules for evaluation of expression?

To evaluate an algebraic expression, you have to substitute a number for each variable and perform the arithmetic operations. In the example above, the variable x is equal to 6 since 6 + 6 = 12. If we know the value of our variables, we can replace the variables with their values and then evaluate the 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.

When evaluating arithmetic expressions the priority order is?

For priority group 1, if two or more operators appear in an expression, the order of priority is right to left within the expression; that is, the rightmost exponentiation or prefix operator has the highest priority, the next rightmost the next highest, and so on.


1 Answers

This is because the parameters in an expression are not specified to be evaluated in any particular order.

The compiler is free to execute either parameter k or lol(&k) first. There are no sequence points in that expression. This means that the side-effects of the parameters can be executed in any order.

So in short, it's not specified whether the code prints 5 or 10. Both are valid outputs.

The exception to this is short-circuiting in boolean expressions because && and || are sequence points. (see comments)

like image 75
Mysticial Avatar answered Sep 28 '22 05:09

Mysticial