I have the following code:
#include <stdio.h>
enum {A, B};
#define C A
int main() {
#if C == B
printf("%d==%d\n", C, B);
#else
printf("%d!=%d\n", C, B);
#endif
}
which, surprinsingly, gives the output:
0==1
Now, I understand that the code is wrong, because enum values are unknown to the preprocessor. What I don't understand is why no error is generated... A and B should be undefined at preprocessing time, how is that the preprocessor gives no error?
An enum is considered an integer type. So you can assign an integer to a variable with an enum type.
An enum is interpreted by the compiler and not the preprocessor.
An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.
In C++ programming, enum or enumeration is a data type consisting of named values like elements, members, etc., that represent integral constants. It provides a way to define and group integral constants. It also makes the code easy to maintain and less complex.
The preprocessor runs in a separate phase before the compiler proper handles the source. As such it doesn't know anything about symbols in the actual source code (like enumerations or variables).
For the preprocessor the symbol B
is an unknown macro and when used in that context (#if C == B
) it will be equal to zero. Since the symbol A
is also not a macro, it will also evaluate to zero. All this lease to the comparison #if 0 == 0
which is indeed true.
See e.g. this phases of translation reference for more information about translation phases, and this preprocessor conditional reference for more information about that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With