Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to resolve macro precedence in C?

I was trying to write a simple C program. Here I have defined a macro.

#define NAME(x) #x ## _bingo

Now which one (# and ##) of them will be solved first?

I am stuck :) . I tried to google about such macro precedence. But couldn't find anything relevant.

like image 369
Amit Bhaira Avatar asked Sep 12 '13 09:09

Amit Bhaira


1 Answers

Now which one (# and ##) of them will be solved first?

The standard says:

16.3.2 The # operator [cpp.stringize]

2/ [...] The order of evaluation of # and ## operators is unspecified.

But what are you trying to achieve here? It seems that:

#define NAME(x) x ## _bingo

Would be enough if you want to concatenate the x token and _bingo.

Example:

NAME(foo)

would be expanded as

foo_bingo

EDIT :

If you want to stringify the generated token with the NAME macro, here is an example on how you can do this (solve the problem of macro replacement -> 16.3.1 of the standard):

#define NAME(x)  x##_bingo

// Converts the parameter x to a string after macro replacement
// on x has been performed if needed.
#define STRINGIFY(x)    DO_STRINGIFY(x)
#define DO_STRINGIFY(x) #x
 
int main() {
    std::string n  = STRINGIFY( NAME( foo ) );
    std::string n2 = DO_STRINGIFY( NAME(foo) );
    
    // Will print foo_bingo as expected
    std::cout << n << std::endl;
    
    // Will print NAME( foo ) because the macro NAME is not expanded
    std::cout << n2 << std::endl;
    return 0;
}

Output:

foo_bingo
NAME(foo)
like image 167
Pierre Fourgeaud Avatar answered Nov 09 '22 14:11

Pierre Fourgeaud