Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a C macro's value is empty

I need to write some code to verify that a macro is defined but empty (not having any values). The test does not need to be in compile time.

I am attempting to write:

#if (funcprototype == "")
MY_WARN("funcprototype is empty");
#endif

the code does not compile, as funcprototype expands to empty.

like image 750
cuteCAT Avatar asked Nov 26 '10 18:11

cuteCAT


People also ask

How do you check if a macro is defined in C?

Inside of a C source file, you can use the #ifdef macro to check if a macro is defined.

How do you define an empty macro?

The preprocessor performs literal substitution with all macros. Therefore, if you define an "empty" macro, then each place that identifier appears in your code will be replaced with an empty statement by the preprocessor before the compiler ever runs.

Does macro do type checking?

In macros, no type checking(incompatible operand, etc.) is done and thus use of macros can lead to errors/side-effects in some cases. However, this is not the case with functions. Also, macros do not check for compilation error (if any).


1 Answers

If a run-time check is okay, then you can test the length of the stringized replacement:

#define REAL_STRINGIZE(x) #x
#define STRINGIZE(x) REAL_STRINGIZE(x)

if (STRINGIZE(funcprototype)[0] == '\0') {
    // funcprototype expanded to an empty replacement list
}
else {
    // funcprototype expanded to a non-empty replacement list
}

I don't think there is a general-case "is this macro replaced by an empty sequence of tokens" compile-time check. That is a similar problem to "is it possible to compare two sequences of tokens for equality," which is impossible to do at compile-time.

like image 178
James McNellis Avatar answered Sep 20 '22 10:09

James McNellis