Do C++ enums Start at 0?

南楼画角 提交于 2019-11-30 04:12:17

Per that standard [dcl.enum]

The enumeration type declared with an enum-key of only enum is an unscoped enumeration, and its enumerators are unscoped enumerators. The enum-keys enum class and enum struct are semantically equivalent; an enumeration type declared with one of these is a scoped enumeration, and its enumerators are scoped enumerators. The optional identifier shall not be omitted in the declaration of a scoped enumeration. The type-specifier-seq of an enum-base shall name an integral type; any cv-qualification is ignored. An opaqueenum-declaration declaring an unscoped enumeration shall not omit the enum-base. The identifiers in an enumerator-list are declared as constants, and can appear wherever constants are required. An enumeratordefinition with = gives the associated enumerator the value indicated by the constant-expression. If the first enumerator has no initializer, the value of the corresponding constant is zero. An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one.

Emphasis mine

So yes if you do not specify a start value it will default to 0.

I would really like to see an answer that confirms this for C++, but I'd also like to know if an ordinal 0 holds even if I specify a value in the middle of an enum:

This also works. It will start at 0 and increment up along the way. Then after the enum you assign the value to it will begin to increase from that value for the next ones.

From the C++11 specification (7.2/2):

If the first enumerator has no initializer, the value of the corresponding constant is zero. An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one.

So yes, the first identifier in the enumeration will have the value zero (if it's not explicitly initialized to another value), and each consecutive identifier will have the value of the previous plus one.

from § 7.2, p 165

. If the first enumerator has no initializer, the value of the corresponding constant is zero

source: http://open-std.org/JTC1/SC22/WG21/docs/papers/2015/n4527.pdf

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