Search code examples
cc-preprocessorparenthesesoperator-precedence

not understanding how the output is generated


i expect the output (or value of silly) to be 36. but what i get is 14. this is fixed when i add parentheses: #define THING (4+2).

but i still want to know what is happening when there are no parentheses and why im getting an output of 14 . the following is my code:

#include <stdio.h>
#include <stdlib.h>

#define THING 4+2

int main(void)
{

    int silly = THING * THING;
    printf("%d", silly);

    return EXIT_SUCCESS;
}

Solution

  • THING*THING = 4+2*4+2 = 4+(2*4)+2 // because of higher precedence of * than +
                = 4+8+2 = 14.
    

    Do remember that MACROs are exactly replaced(substituted) into the code.