Вопрос

I was wondering if Boolean is a built-in enumeration. According to Wikipedia ~

"Some enumerator types may be built into the language. The Boolean type, for example is often a pre-defined enumeration of the values FALSE and TRUE."

http://en.wikipedia.org/wiki/Enumerated_type

In C and other languages, is Boolean an Enum? And if not - can you explain why?

Это было полезно?

Решение

The question is much more of an abstract, philosophical question about "what is a type" than it is about C. In C, everything (more or less) is an integer at heart, but that misses the point.

When you say "integer" you are usually referring to an arithmetic type, i.e. one for which arithmetic operations like addition and multiplication make sense.

By contrast, an enumerative type is a type that only holds a collection of discrete values which have no further structure among them. The only property an enumerative value has is itself; there are no operations on it other than checking for equality.

Forgetfully, the integers are also an enumerative type (they enumerate the number of shoes you can have on your shoe rack, as well as the sizes of herds of sheep), but there's more to them - they have an internal structure given by the arithmetic operations they admit.

A boolean value can similarly be considered an enumerative type by forgetting its operations, and only considering that it enumerates two states, true and false. However, booleans also have a whole set of operations defined on them, given by the logical operations (and, or, not, etc.), which makes them different from plain enums. In that sense, booleans are much closer to "one-bit integers" than to "enums".

In summary, every discrete type can be thought of as an enum (and is handles identically by most hardware), but enums are the "weakest" of the discrete types, having no structure beyond their identity. By contrast, integers and booleans are discrete types with additional (respectively arithmetic and logical) structure.

Другие советы

bool is a native type in C99, and not an enum.

More precisely, bool is a macro defined in stdbool.h that expands to _Bool, which is the actual native type.

The difference is that a bool can hold only true or false (which are macros that expand to 1 and 0), while an enum can be assigned any integral value.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top