Insignificant Person
Insignificant Person

Reputation: 913

When Is Order Of Evaluation Important

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?

Upvotes: 1

Views: 147

Answers (2)

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

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);

Upvotes: 4

2501
2501

Reputation: 25753

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.

Upvotes: 2

Related Questions