Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associativity of function call operator in C

I was going through the topic of associativity of C operators.

There I came across this fact that the function call operator () has a left to right associativity. But associativity only comes to play when multiple operators of the same precedence occur in an expression. But I couldn't find any example involving function call operator where associativity plays a crucial role.

For example in the statement a = f(x) + g(x);, the result depends on the evaluation order and not on the associativity of the two function calls. Similarly the call f(g(x)) will evaluate function g() first and then the function f(). Here we have a nested function call and again associativity doesn't play any role.

The other C operators in this priority group are array subscript [], postfix ++ and postfix --. But I couldn't find any examples involving a combination of these operators with () where associativity plays a part in expression evaluation.

So my question is does the associativity of function call being defined as left to right affect any expression in C? Can anyone provide an example where the associativity of function call operator () does matter in expression evaluation?

like image 620
Deepu Avatar asked Aug 10 '15 11:08

Deepu


People also ask

What is the associativity of operator in C?

Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the same precedence. An operator's precedence is meaningful only if other operators with higher or lower precedence are present. Expressions with higher-precedence operators are evaluated first.

Which is correct associativity for == operator?

The right-associativity of the = operator allows expressions such as a = b = c to be interpreted as a = (b = c) .

Which operators are left associative?

Left-associative operators of the same precedence are evaluated in order from left to right. For example, addition and subtraction have the same precedence and they are left-associative. In the expression 10-4+2, the subtraction is done first because it is to the left of the addition, producing a value of 8.

Which operator has associativity from right to left?

The grouping of operands can be forced by using parentheses. For example, in the following statements, the value of 5 is assigned to both a and b because of the right-to-left associativity of the = operator.


1 Answers

Here is an example, where left-right associativity of function call operator matters:

#include <stdio.h>  void foo(void) {     puts("foo"); }  void (*bar(void))(void) // bar is a function that returns a pointer to a function {     puts("bar");     return foo; }  int main(void) {     bar()();      return 0; } 

The function call:

bar()(); 

is equivalent to:

(bar())(); 
like image 60
Grzegorz Szpetkowski Avatar answered Sep 21 '22 05:09

Grzegorz Szpetkowski