Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the value of an undefined constant used in #if?

My preprocessor appears to assume that undefined constants are 0 for the purpose of evaluating #if conditions.

Can this be relied upon, or do undefined constants give undefined behaviour?

like image 965
Tony Park Avatar asked Feb 22 '11 23:02

Tony Park


People also ask

What is undefined constant?

Referring to a class constant without specifying the class scope.

What is the value of undefined in C?

C has no specific undefined value. A function that wants to return an undefined value might indicate failure. Sometimes -1 is failure, sometimes 0 is failure, sometimes 0 is success; one has to look up the documentation to know exactly which. For a pointer, the undefined value is often pointer 0, the NULL pointer.

Is defined constant PHP?

PHP Constants Checking if constant is definedTo check if constant is defined use the defined function. Note that this function doesn't care about constant's value, it only cares if the constant exists or not. Even if the value of the constant is null or false the function will still return true .


2 Answers

Yes, it can be relied upon. The C99 standard specifies at §6.10.1 ¶3:

After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers are replaced with the pp-number 0

Edit

Sorry, I thought it was a C question; still, no big deal, the equivalent section in the C++ standard (§16.1 ¶4) states:

After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers and keywords, except for true and false, are replaced with the pp-number 0

The only difference is the different handling of true and false, which in C do not need special handling, while in C++ they have a special meaning even in the preprocessing phase.

like image 126
Matteo Italia Avatar answered Sep 25 '22 12:09

Matteo Italia


An identifier that is not defined as a macro is converted to 0 before the expression is evaluated.

The exception is the identifier true, which is converted to 1. This is specific to the C++ preprocessor; in C, this doesn't happen and you would need to include <stdbool.h> to use true this way, in which case it will be defined as a macro and no special handling is required.

like image 22
James McNellis Avatar answered Sep 24 '22 12:09

James McNellis