简体   繁体   中英

Nested function calls order of evaluation

It's well-known that the order of evaluation of a function's arguments in unspecified and can differ between different compilers.

What doesn't seem so clear is whether function calls can be interleaved, in the following sense:

f(g(h()), i(j()))

Let's assume the compiler chooses to evaluate f's first parameter first. Is the compiler free to call j between calling h and g ? I believe so, but I don't know where to find confirmation in the Standard.

The evaluation order is unspecified - see section 5.2.2/8 of the Standard:

The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered.

I don't know what the standard says, but I think that if it matters to you, then you should probably re-arrange the code so that you know what's going to happen in which order (temp variables are your friends). Even if you figure out what the standard says, AND if we assume that your compiler implements that correctly, you're still leaving a maintenance time bomb, because your successors WON'T know everything you do.

The evaluation order is not specified by the standart. It depends only on your compiler.

If the functions you're using in the same expression are somehow related (one affects the results of the other), so different order of calls give different results, then refrain of using nested functions in expressions.

I do it as good practice, exactly because, as the other said, the calling order is undefined (you could have even interlaced execution, if the optimizer thought it will be more optimal).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM