Conditional-Operator in Constant Expression

末鹿安然 提交于 2019-12-14 01:23:50

问题


I tried the following code snippet with MSVC 10, where it works fine.

enum
{
  FOO = (sizeof(void*) == 8 ? 10 : 20)
};

int main()
{
  return FOO;
}

What I would like to know is: Does the C++ Standard (preferably C++98) allow me to use the conditional-operator in a constant expression when all operands are constant expressions, or is this a Microsoft quirk/extension?


回答1:


This is perfectly valid and sensible standard C++.

The ternary conditional operator forms an expression, and the expression is a constant expression if its operands are.

The standard reference is C++11 5.19/2:

A conditional-expression is a core constant expression [...]

Note that by 5.16, ternary conditional expressions are one type of conditional-expressions. Other types are things like 2 == 3.



来源:https://stackoverflow.com/questions/16549631/conditional-operator-in-constant-expression

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