Question

What is the execution sequence of the following statement:

x = f(2) * g(5) + h();

I have seen this link, the precedence order should be f, g and h. Am I right or not, please explain

Was it helpful?

Solution

In this case, you can't make any guarantees about the order of execution of the functions.

While precedence rules imply that f(2) will be multiplied by g(5) before h() is added to the result, the order of execution of these sub-expressions is implementation-defined.

If you're doing this with functions that have side-effects, don't. Depending on the code, you may or may not see different results from compiler to compiler.

Note: As @Jakub Zaverka mentions, there are slightly different rules when you're dealing with logical operators && or || because of features like short-circuiting.

OTHER TIPS

f(2), g(5) and h() are executed in any sequence.

The results of f() and g() are multiplied. That product is then added to the result of h().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top