Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using enum values in preprocessor directive

Tags:

c

preprocessor

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?

like image 461
Emanuele Paolini Avatar asked Aug 30 '18 14:08

Emanuele Paolini


People also ask

Can we assign value to enum in C?

An enum is considered an integer type. So you can assign an integer to a variable with an enum type.

Is enum preprocessor?

An enum is interpreted by the compiler and not the preprocessor.

How do you declare an enum variable?

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.

How does enum work C++?

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.


1 Answers

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.

like image 180
Some programmer dude Avatar answered Nov 15 '22 05:11

Some programmer dude