简体   繁体   中英

Macros argument order matters?

When i compile the below program following error is generated by the compiler.

example.cpp:12:13: error: invalid operands to binary expression ('const char *' and 'const char *')
cout << JMP(to_string(10)) << endl;

        ^~~~~~~~~~~~~~~~~~
example.cpp:6:34: note: expanded from macro 'JMP'
#define JMP(add) "DEFAULT is : " + DEFAULT + " JMP is : " + add

           ~~~~~~~~~~~~~~~ ^ ~~~~~~~

#include <iostream>
#include <string>

#define DEFAULT "00000"
#define JMP(add) "DEFAULT is : " + DEFAULT + " JMP is : " + add

using namespace std;

int main()
{
   cout << JMP(to_string(10)) << endl;
   return 0;
}

Whereas the below program compiles properly

#include <iostream>
#include <string>

#define DEFAULT "00000"
#define JMP(add) "JMP is : " + add + "DEFAULT is : " + DEFAULT

using namespace std;

int main()
{
   cout << JMP(to_string(10)) << endl;
   return 0;
}

Why the order of argument present in the macro body matters ?

Try to get rid of the + to concatenate char array literals:

#define JMP(add) "DEFAULT is : " DEFAULT " JMP is : " add

NOTE: Since add will expand to a std::string value ( to_string(10) ) from your sample, this won't work either. You'll need to call the macro like this:

cout << JMP("10") << endl;

An alternate solution would be making the parts std::string instances:

#define JMP(add) std::string("DEFAULT is : " DEFAULT " JMP is : ") + add

The error is telling you that the operands given to the binary expression (ie + operator ) are not of expected types. This operator is expecting a const string & (or a string & using C++ 11) for at least one of its operands. That plus left to right evaluation is why it works when you switch the order.

cout << to_string(10) + " is the JUMP" << endl; // having valid operands, + operator returns a string object
cout << "JUMP is : " + to_string(10) << endl;   // same here
cout << "DEFAULT is : " + "00000" << endl;      // no bueno: both operands are const char pointers

Provided that you have a const string & as a starter* , you can keep concatenating const char * s all day long:

cout << "JUMP is : " + to_string(10) + " DEFAULT is : " + "00000" + "game is " + "concentration, " + "category is " + "..." << endl;

So, this actually is not about order of macro arguments but about strings, char pointers, concatenation, associativity, and operators.

*as in a sports game.

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