Idan
Idan

Reputation: 227

using "define" in C language both as int and as char

I'm trying to use a #define such us the following, as int and as char

#define name joe

This way it's int, but I want to be able to printf this #define and get the word Joe. I know I can use

#define name "Joe"

But then I will gave up its "int abilities".

what can I do? thx guys!

Upvotes: 0

Views: 744

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 224546

The # preprocessor operator turns a macro parameter into a string literal. The output of:

#include <stdio.h>

#define name            Joe
#define Helper(x)       #x
#define Stringify(x)    Helper(x)

int main(void)
{
    int name = 4;
    printf("%s is %d.\n", Stringify(name), name);
}

is:

Joe is 4.

Two macros are necessary because the expansion of x in for Stringify would not be performed until after the # is applied. So we need Stringify to expand x and then Helper to produce the string literal.

Do not use this in production code without good reason. Playing games with the preprocessor should be used carefully.

Upvotes: 3

Related Questions