2014年2月26日 星期三

#define in C is expands textually

#include<stdio.h>
#define square(x) x*x
main() 
{
    int x = 2;
    printf("%d\n", square(x + 1));
    return 0;
}

The answer is 5 not 9, because the preprocessor expands it textually like below.

x * x = 2+1 * 2+1 = 2+(1*2)+1=2+2+1=5
That is not function. We can fix it as

#define square (x) (x)*(x) 
or
#define square (x) ((x)*(x)) 


沒有留言:

張貼留言