Why this operation is not following the precedence and associativity table in C?

70 Views Asked by At

I was trying to learn about difference between functions and macro with arguments (aka 'macro function' ?) and i got this code:

#include <stdio.h>

#define mult_m(a) a*a 

int mult_f(int a){
    return a*a;
}

int main()
{
    int x=3,y=3,z=3;
    //printf("%d\n",mult_m(x++));
    //printf("%d\n",mult_f(++y));
    printf("%d\n",++z * z++);
    printf("%d\n",z);

    return 0;
}

The output is: 20

I know about precedence and associativity and this ouput does not make sense to me, in my headcannon this should be:

  • Postfix increment have higher precedence than * or prefix ++ so: ++z * 3++ ---> ++z * 3 (z now is equal to 4) ---> ++4 * 3

  • The * and prefix ++ have same precedence so the associativity is right to left so: ++4 * 3 ---> 5*3=15

HEADCANNON OUPUT: 15

ACTUAL OUTPUT: 20

Can you explain me why this is happening? if you have a C standard reference to explain this i would really appreciate it

Thanks in advance!

1

There are 1 best solutions below

0
On

Can you explain me why this is happening?

Yes, because it invokes undefined behaviour as you have unsequenced modifications of the variable z.

If you enable warnings the compiler will warn you about it

<source>:23:19: warning: operation on 'z' may be undefined [-Wsequence-point]

This is one of the reasons why macros can be very dangerous. Your square macro if used with post or pre increment operator will invoke UB too.