简体   繁体   中英

Clarification of C Operator Associativity

I'm reading " The C Programming Language " book, and I came across the following line (paraphrasing):

"...in expressions like x = f() + g();

f() maybe called before g() or vice versa. C doesn't specify the order in which the operands will be evaluated..."

But, according to precedence and association rules, doesn't functions calls have highest precedence? And, since the associativity of the function call operator () is from "left to right", shouldn't f() be called before g() (definitely) ?

But, according to precedence and association rules, doesn't functions calls have highest precedence?

The function calls have highest precedence. It means that both f() and g() will be evaluated before "+" is evaluated. It does not mean that f() will be evaluated before or after g().

And, since the associativity of the function call operator () is from "left to right", shouldn't f() be called before g() (definitely) ?

No, it shouldn't. The operator () has left to right associativity. It means that in expression f(x)(y) (can have it in C if the function f returns another function), f(x) is calculated first and then the resulting function is applied to y . It does not mean that f() will be evaluated before or after g().

This is neither the case of precedence or associativity in the way you refer to.
Simply, f() and g() will be evaluated in whatever order before + is applied and then their results will be added to produce x .

Associativity and operator precedence only matter when you can write a construct that is ambiguous without them. In a + b * c , operator precedence requires b * c to be evaluated first. In a + b + c , associativity requires a + b to be evaluated first, when the program can tell the difference (such as when a , b , and c are floating point values).

In f() + g() , operator precedence does come into it a little; it says that f and g are the functions being called, as opposed to f and f() + g , which is what would happen if addition had higher precedence, and it also says that both function calls happen before the addition. Associativity, though, is irrelevant , because the addition is in the middle. I don't think it's even possible to write the equivalent of a + b + c with function-call operators, because the function-call operator is asymmetric.

Neither associativity nor operator precedence controls which function call is evaluated first. The only guarantee you have is that one of them is evaluated first — if there's any way for you to observe this, their execution can't be interleaved.

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