Why is C99's bool a macro rather than a typedef?

痞子三分冷 提交于 2019-12-24 08:59:26

问题


Why does the boolean type support introduced in C99 use the preprocessor rather than the language's own facilities? Specifically, why do we have:

#define bool    _Bool
#define true    1
#define false   0

in <stdbool.h> rather than:

typedef _Bool bool;
enum { false = 0, true = 1 };

I guess the enum can be seen as a matter of taste. But - why not have a typedef?


回答1:


From section 7.18/3 of the C11 specification:

The remaining three macros are suitable for use in #if preprocessing directives.

The specification lists true, false and __bool_true_false_are_defined.

The specification also continues to state (in 7.18/4) that the bool, true and false macros may be undefined by a program.

The last part, about undefining them, is (I guess) because of much legacy code when C99 was published used their own definitions and variations of the boolean types and values. So it would not invalidate existing code. So they are macros so they can be used in preprocessor conditions, and so they can be undefined by a program.



来源:https://stackoverflow.com/questions/49277769/why-is-c99s-bool-a-macro-rather-than-a-typedef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!