1

I've read order of evaluation of expressions in function arguments and binary operators are undefined in C. What this means and when should I be careful about it?

Insignificant Person
  • 863
  • 2
  • 10
  • 24
  • 2
    possible duplicate of [Explain the order of evalution in printf](http://stackoverflow.com/questions/12960241/explain-the-order-of-evalution-in-printf) – 2501 Oct 12 '14 at 12:12
  • 2
    possible duplicate of [Parameter evaluation order before a function calling in C](http://stackoverflow.com/questions/376278/parameter-evaluation-order-before-a-function-calling-in-c) – WhozCraig Oct 12 '14 at 12:13
  • You know what "*evaluation of [an] expression[s]*" means/is? – alk Oct 12 '14 at 12:18

2 Answers2

4

Just don't depend on it. If you have code like:

func(a(), b(), c());

Then the order of execution of a(), b() and c() shouldn't matter for the correctness of your program. If it does (for example, if a() opens a resource and c() closes it), then you have something dangerous here.

The most simple workaround is to write such code like this:

int a_result = a();
int b_result = b();
int c_result = c();
func(a_result, b_result, c_result);
Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
1

Here is a simplified example:

SomeCall( Writefile( handle ) , Closefile( handle ) ) ;

In what order the two function are called in not specified and you may close the file before you even get to write into it, even though the order of the calls logically appears correct.

2501
  • 25,460
  • 4
  • 47
  • 87
  • Why does it "logically appear correct"? It appears to me like you're doing to things that should be ordered without order, i.e. not correct. – Kerrek SB Oct 12 '14 at 12:43
  • @KerrekSB Because we read from left to right, and down. The code might as well be sectioned into separate lines for example. Remember OP is not a c expert and logic does play a role. – 2501 Oct 12 '14 at 12:43