Home > Net >  Literal '#' character in C preprocessor macro replacement-list?
Literal '#' character in C preprocessor macro replacement-list?

Time:12-03

Is there any way in which we can have literal '#' character in replacement-list of C preprocessor macro?

'#' character in replacement-list of C preprocessor is an operator that performs stringification of argument, for example-

#define foo(words) #words

foo(Hello World!)

will result-

"Hello World!"

Is there any way we can have '#' as a literal character in replacement-list like-

#define foo(p1, p2) p1 # p2
                    // ^ is there any way to specify that- this isn't # operator?
foo(arg1, arg2) // will result-
arg1 "arg2"
// What I wanted was
// arg1 # arg2

I tried a macro like-

#define foo(p1, p2, p3) p1 p2 p3
// And then
foo(arg1, #, arg2)
// Which resulted in
arg1 # arg2

This was getting the work done but wasn't better than typing arg1 # arg2 manually.

Then I tried defining a foo macro which in turn will call metafoo with '#' as argument-

#define metafoo(p1, p2, p3) p1 p2 p3
#define foo(p1, p2) metafoo(p1, #, p2)
foo(arg1, arg2)

which resulted in a error error: '#' is not followed by a macro parameter, because # was getting interpreted like stringification operator.

CodePudding user response:

This is easily solved with:

#define NumberSign  #
#define foo(p1, p2) p1 NumberSign p2

foo(arg1, arg2)

which yields:

arg1 # arg2

The reason it works is that # is an operator in function-like macros (macros with parameters) but has no effect in object-like macros (macros without parameters).

CodePudding user response:

What about this?

#define metafoo(p1, p2, p3) p1 p2 p3
#define hash #
#define foo(p1, p2) metafoo(p1, hash, p3)
foo(arg1, arg2)

In foo you probably mean p2 instead of p3.

CodePudding user response:

This is a bit different from literally expanding your macro to arg1 # arg2, but assuming you want to use arg1 # arg2 as a string - e.g. you want printf(foo(arg1, arg2)) to be equivalent toprintf("arg1 # arg2"), you can write:

#define foo(arg1, arg2) #arg1 "#" #arg2
  •  Tags:  
  • cgcc
  • Related