Unable to get the logic behind the priority of the macro and operators

advertisements

The output of the following code is 8 24 32. I understand the logic behind 8 and 24 but 32 seems very strange to me. Can somebody explain why it prints 32?

#define cube(x) x*x*x
void main()
{
    printf("%d ",cube(2));
    printf("%d ",16+cube(2));
    printf("%d ",16/cube(2));
}


The last printf gets translated to :

printf("%d ",16/2 * 2 * 2);

And that is why all macros should have surrounding parentheses:

#define cube(x) ((x)*(x)*(x))

Or just use functions and trust the compiler to inline them. Functions are almost always better.