What are some tricks I can use with macros? [closed]

In C, it’s common to define macros that do some stuff getting the verbatim argument, and at the same time define functions to be able to get the address of it transparently. // could evaluate at compile time if __builtin_sin gets // special treatment by the compiler #define sin(x) __builtin_sin(x) // parentheses avoid substitution by … Read more

Macros to create strings in C

In C, string literals are concatenated automatically. For example, const char * s1 = “foo” “bar”; const char * s2 = “foobar”; s1 and s2 are the same string. So, for your problem, the answer (without token pasting) is #ifdef __TESTING #define IV_DOMAIN “example.org” #elif __LIVE_TESTING #define IV_DOMAIN “test.example.com” #else #define IV_DOMAIN “example.com” #endif #define … Read more

C Preprocessor, Stringify the result of a macro

Like this: #include <stdio.h> #define QUOTE(str) #str #define EXPAND_AND_QUOTE(str) QUOTE(str) #define TEST thisisatest #define TESTE EXPAND_AND_QUOTE(TEST) int main() { printf(TESTE); } The reason is that when macro arguments are substituted into the macro body, they are expanded unless they appear with the # or ## preprocessor operators in that macro. So, str (with value TEST … Read more

# and ## in macros

An occurrence of a parameter in a function-like macro, unless it is the operand of # or ##, is expanded before substituting it and rescanning the whole for further expansion. Because g‘s parameter is the operand of #, the argument is not expanded but instead immediately stringified (“f(1,2)”). Because h‘s parameter is not the operand … Read more

What are the applications of the ## preprocessor operator and gotchas to consider?

One thing to be aware of when you’re using the token-paste (‘##‘) or stringizing (‘#‘) preprocessing operators is that you have to use an extra level of indirection for them to work properly in all cases. If you don’t do this and the items passed to the token-pasting operator are macros themselves, you’ll get results … Read more