Search code examples
cmacrosoutputpreprocessor

Unexpected output in expression that uses macros


My code:

#include <stdio.h>
#define PRODUCT(x) (x * x)

int main()
{
    int i = 3, j, k, l;
    j = PRODUCT(i + 1);
    k = PRODUCT(i++);
    l = PRODUCT(++i);
    printf("%d %d %d %d", i, j, k, l);
    return 0;
}

I am not able to comprehend why the output is:

7 7 12 49. 

Is there any error in macro or some other problem?


Solution

  • Your macro is incorrect. The following expression:

    PRODUCT(i+1)
    

    will expand to

    (i+1 * i+1)
    

    which is 2*i+1.

    Your macro should be:

    #define PRODUCT(x) ((x)*(x))
    

    I strongly suggest you stop using macros for this sort of thing. You could easily write this as a function:

    int product(int x)
    {
      return x * x;
    }
    

    Note that this will only work for the example I gave. If you try

    PRODUCT(i++)
    

    you will get

    ( (i++) * (i++) )
    

    which invokes undefined behaviour, as this expression lacks a sequence point between the 2 increments.