Home > other >  Change C/C Preprocessor priority
Change C/C Preprocessor priority

Time:01-18

I want to change the priority of the preprocessor define process.

see the following code:

#include <iostream>
#include <sstream>

#define $(x)  <<  x  <<  
#define f(x) (#x) 


int main()
{
    auto world = "universe!";

    std::stringstream ss;

    ss <<  f(Hello $(world)) << std::endl;

    std::cout << ss.str();

    return 0;
}

The code run, but the 'f' macro will always processed before the '$' macro.

The current output:

Hello $(world)

Expected output:

Hello universe!

Thx.

CodePudding user response:

"Solving" the problem:

#include <iostream>
#include <sstream>

#define $(x)  << " " << x   
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define f(x, y) TOSTRING(x) y

int main()
{
    auto world = "universe!";

    std::stringstream ss;

    ss << f(Hello, $(world)) << std::endl;

    std::cout << ss.str();

    return 0;
}

Output:

Hello universe!

CodePudding user response:

You might "delay" expansion with extra indirection:

#define $(x)  <<  x  <<  
#define STRINGIFY(x) #x
#define f(x) STRINGIFY(x)

but you won't get your expected result but Hello << world << Demo

Without changing your MACRO, you might already get your result by "fixing" your parenthesis (and surrounding):

ss <<  f(Hello) " " $(world) /*<<*/ std::endl;

Demo.

  • Related