简体   繁体   中英

string concatenation in macro C

In C, I have two macros

Edit:

#define macro1(name , number , date ){\
 <---------body------>
 }


#define macro2(key){\
 <------body----->
 }

I have to combine the name( a char * variable) , number (an integer) , date(another char* variable) and send it as a string to the macro2 which will be called from the macro1 .

I'm trying to do it by declaring a char* variable in macro 1 and use snprintf. Is this a good idea ?

PS : I'm converting the into a string and then combining them.

Function in c++:

std::string concat(const std::string& name, int number, const std::string& date)
{
    return name + std::to_string(number) + date;
}

Macro for literals c-strings:

#define MACRO(name, number, date) name #number date

If you do this with macros, it will get too big and messy.

Instead of macros, you can do this with inline function. This is more C++ way, but it will work great in C too:

inline const char *macro1(const char *name, int const number, const char *date, char *buffer, size_t const buffer_size){
    // copy everything into the buffer, probably with sprintf()
    return buffer;
}

in case of C, I also suggest function to be defined as:

static inline const char *macro1(const char *name, int const number, const char *date, char *buffer, size_t buffer_size);

but this will not always compiled in C++.

Update:

As 5gon12eder mentioned, it does compiles on gcc 6.2.1 and clang 3.8.1.

For C++ instead of static you can use anonymous namespace:

namespace{
    inline const char *macro1(const char *name, int const number, const char *date, char *buffer, size_t buffer_size);
}

Finally, if you plan to use the string just to print it, or put it into a file, do not concatenate, but just do it in this function.

#define STR1  "wel "

#define STR2  "come"

#define STR3  STR1 ## STR2

OR

#define STR1  "wel "

#define STR2  "come"

#define STR3 STR1 STR2

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