开发者

macro substitution

# include <开发者_运维知识库stdio.h>
# define ONE 1
# define TWO 2
# define ONE TWO
# define TWO ONE
int main ( void )
{
  printf("ONE = %d, TWO = %d\n", ONE, TWO );
  return 0;
}

what actually happens when we write this way? In the 4th line #define ONE TWO, does the pre processor replace it blindly as 1 2 immediately?


If you are using xcode 3 you could do a right click on the file and select PreProcess

You will get a huge file with this code near the end

int main ( void )
{
 printf("ONE = %d, TWO = %d\n", ONE, TWO );
 return 0;
}

Edit: I see it's useless in this case. For some reason the preprocess happens without error and warnings, but the code doesn't change. But if you write useful code you can look at the preprocessed code.


and if you try to compile it you get a bunch of warnings and errors.

test.c:4:1: warning: "ONE" redefined
test.c:2:1: warning: this is the location of the previous definition
test.c:5:1: warning: "TWO" redefined
test.c:3:1: warning: this is the location of the previous definition
test.c: In function ‘main’:
test.c:8: error: ‘ONE’ undeclared (first use in this function)
test.c:8: error: (Each undeclared identifier is reported only once
test.c:8: error: for each function it appears in.)
test.c:8: error: ‘TWO’ undeclared (first use in this function)


conflict of which macro will be called will be arised.....as ONE is 1 and ONE is TWO.... that is linking error.


In the 4th line #define ONE TWO, does the pre processor replace it blindly as 1 2 immediately?

No. The relevant form of the define directive in this case is:

#define identifier replacement-list new-line

... and there is no replacement happening on identifier. Also, the following applies:

An identifier currently defined as an object-like macro shall not be redefined by another #define preprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical.

... which makes your redefinition illegal.

If you need to redefine a macro, you have to undefine it first using #undef.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜