Which came first?

closed account (o1vk4iN6)
Can it be assumed that functions are evaluated before any arithmetic calculation?

1
2
3
4
5
6
7
8
9
10
11
12
void foo(int* i)
{ *i += 10; }

void main()
{
     int a = 10, b, c;

     b = (a / 2) + foo(&a); // foo executed first?
     c = foo(&a) + (a / 2); // foo still executed first?
     
}
No, it cannot.
foo() can be executed before or after a/2, and the order may change the second time you evaluate the same line of code. C++ (or C for that matter) has no order of evaluation (except for a few special cases)

Incidentally, you have an error: main() cannot return void and foo() must return something in order for those expressions to compile.
Last edited on
Program flow is controlled by sequence points. Usually that's the good old semicolon.

Anything between sequence points can be evaluated in any order the compiler chooses, as long as operator precedence rules are followed.

Therefore, in this case, there is no way to guarantee that foo() is evaluated first.

If you want to guarantee it, just do the obvious:

1
2
b = foo(&a);
b += (a/2);
Topic archived. No new replies allowed.