简体   繁体   中英

C preprocessor replacement not working

#include <stdio.h>
#define VAR cc

int main(void) {
    int ccc = 9;
    printf("hell loo %d", VARc);
    return 0;
}

My understanding of this code means that anywhere the preprocessor finds VAR , it will replace it with cc , hence the printf will have a proper defined variable ccc , but the code errors out. Can someone please help


EDIT 1

Error that I am getting is

 test.c: In function 'main': test.c:16: error: 'VARc' undeclared (first use in this function) test.c:16: error: (Each undeclared identifier is reported only once test.c:16: error: for each function it appears in.) 

That won't work. The preprocessor works on whole tokens, not strings.

If you want concatenation, you can do:

#include <stdio.h>
#define VAR(End) cc##End // ## does token concatenation inside a pp macro

int main(void) {
    int ccc = 9;
    printf("hell loo %d", VAR(c));
    return 0;
}

The reason why that was not working is:

Tokenization precede preprocessing in other words identifying tokens from the preprocessing file comes before macro expansion.

As CPP is greedy , it will consider VARc as a single token relating to identifier category and which is different from VAR in macro definition. That's why it cannot be replaced.

So one of solution is to use concatenation or create another macro for VARc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM