Reputation: 83
result= function_1()*function_2();
I am writing a code like above. What I want to know is while doing the multiplication, which function is called first? That is because, the first called function can effect the result returned from the other function. I assumed function_1()
is called first, and when I tried I saw that it is really so. However, is it always the case? Does it depend on which compiler I use or the system I work on?
Upvotes: 3
Views: 1058
Reputation: 311088
According to the C++ Standard (1.9 Program execution)
15 Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.
So in this expression
result= function_1()*function_2();
some compilers can evaluate at first function_1() and then function_2() while other compilers can evaluate at first function_2() and only then function_1(). Even if you write like
result= (function_1())*(function_2());
or
result= (function_1())*function_2();
or
result= function_1()*(function_2());
nothing will be changed relative to the order of evaluation of the operands.
Upvotes: 4
Reputation: 1
Order of evaluation is unspecified by the C++ (or the C) standard (see answer from Vlad). If your function_1
or function_2
have significant side-effects, it may become some unspecified behavior which you should absolutely avoid (like you should avoid undefined behavior). And in some cases (inlined functions with strong optimizations) the computations might be intermixed.
Think about weird cases like
static int i;
int function_1(void) { i++; return i; }
int function_2(void) { i+=2; return 3*i+1; }
It probably is implementation specific, and might depend upon the actual compiler and the optimization flags.
You should code as if the order of function calls is completely random and not reproducible (even if in practice it might be reproducible). Likewise, you should not expect any particular order of arguments evaluation (e.g. in f(i++, ++j)
you don't know if i
or j
has been incremented first), even if for a given compiler that order might be fixed. Again, you should imagine a completely random and non-reproducible order.
As commented by David Schwartz, if you care about the order, you should code explicitly some sequence points
At last, if your code is depending upon some order, it is completely unreadable and for that simple readability reason you should avoid coding this way.
Upvotes: 9