Yola
Yola

Reputation: 19041

Use value of char* variable in macros

Can i have somethig like this?

#include <stdio.h>

#define CAT2(a1, a2) #a1 ## ";" ## #a2

int main(void)
{
    const char *ch1 = "1";
    const char *ch2 = "2";
    puts(CAT2(ch1, ch2));
}

Output:

1;2

But currently i have

ch1;ch2

Upvotes: 1

Views: 1921

Answers (3)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

The # operator replace the parameter given to him by a string literal.

It means that :

#define TO_STR(arg) #arg

const char* ch1 = "1";
TO_STR(ch1)    // <- Will give "ch1"

From the standard :

16.3.2 The # operator [cpp.stringize]

A character string literal is a string-literal with no prefix. If, in the replacement list, a parameter is immediately preceded by a # preprocessing token, both are replaced by a single character string literal preprocessing token that contains the spelling of the preprocessing token sequence for the corresponding argument.

So in you case, you try to concatenate (with the ## operator) :

"ch1" ## ";" ## "ch2"

That explains the result you get.

As the MACRO are evaluted at preprocessing time, you cannot concatenate variables in the way you want to do it.

If you are in C, you should use strcat for example.

If you are in C++, why don't you use std::string or in C++11 you can use snprintf.

Upvotes: 3

Nemanja Boric
Nemanja Boric

Reputation: 22177

You cannot do string concatenation using macros in the way you want.

Use snprintf in order to prepare your string:

char tmp[20];
snprintf(tmp, sizeof(tmp), "%s;%s", ch1, ch2);

Macros are expanded in the compile time, before actual compilation, and it can't know the runtime values.

You can wrap above code into the function that will return tmp (just don't forget to make tmp static variable to prevent leaking).

char* cat2(char *ch1, char* ch2)
{
    static char tmp[50];
    snprintf(tmp, sizeof(tmp), "%s;%s", ch1, ch2);
    return tmp;
}

// inside main
puts(cat2(ch1, ch2));

Upvotes: 1

code_fodder
code_fodder

Reputation: 16371

Unfortunately since macros are eveluated at compile time you cannot use the values of your variables, this is the main limiting factor with macros. I.e. they cannot evaluate run-time values.

Upvotes: 1

Related Questions