Sequence of function calls (C ++)

result= function_1()*function_2();

      

I am writing the code as described above. What I want to know is to do the multiplication, which function is called first? This is because the first function called may affect the result returned from another function. I assumed what was function_1()

called first, and when I tried, I saw that it really was. However, is this always the case? Does it depend on which compiler I'm using or the system I'm working on?

+3


source to share


2 answers


The order of evaluation is not specified by the C ++ (or C) standard (see answer from Vlad ). If yours function_1

or function_2

have significant side effects , this may become some unspecified behavior that you should absolutely avoid (for example, you should avoid undefined behavior ). And in some cases (heavily optimized built-in functions) the calculations can be mixed.

Think of strange cases like

 static int i;
 int function_1(void) { i++; return i; }
 int function_2(void) { i+=2; return 3*i+1; }

      

It is probably implementation specific and may depend on the actual compiler and optimization .



You should code as if the order of the function calls were completely random and not reproducible (even though it might be reproducible in practice). Likewise, you should not expect any particular order in which the arguments are evaluated (for example, f(i++, ++j)

if you donโ€™t know if the first step was i

or j

), even if this order could be corrected for a given compiler. Again, you must present a completely random and non-reproducible order.

As David Schwartz commented , if you care about ordering, you must explicitly specify the sequence point code

Finally, if your code depends on some order, it is completely unreadable and for that simple readability you should avoid coding in this way.

+9


source


According to the C ++ standard (version 1.9)

15 Except where noted, the evaluations of the operands of individual operators and subexpressions of individual expressions are not affected.

So in this expression

result= function_1()*function_2();

      

some compilers may evaluate function_1 () first and then function_2 (), while other compilers may evaluate function_2 () first and 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 regarding the order of evaluation of the operands.

+4


source







All Articles