Jump to content

Order of Evaluations

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
atrip25

atrip25

    Newbie

  • Members
  • PipPip
  • 26 posts
what could be the result based on different orders of evaluation? I'm not sure I totally understand order of evals? Is there different ways this code can be read or executed?

int fun(int *i) {

 	    (*i) += 5;

 	    return 4;    

	}

	

	int main() {

  	    int x = 3;	

  	    x = x + fun(&x);

	}


#2
Hignar

Hignar

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 420 posts
Most programming languages will evaluate the right hand side of an assignment operation first. In your example
 x = x + fun(&x); 
the RHS will be evaluated first
 x + fun(&x)
Things are slightly complicated by the fact that you use fun() to alter the value of x, but again the RHS is evaluated first. fun() returns 4 but it has altered the value of x to 8 so the x on the LHS of the '+' is evaluated as 8. Thus the whole RHS of the assignment operation evaluates to 12, which is then assigned to x.
If there's a new way, I'll be the first in line.

But, it better work this time.

#3
JCoder

JCoder

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 245 posts
This is undefined behaviour. You should never rely on order of evaluation of the operators other than && || !