3

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?

mooware
  • 1,722
  • 2
  • 16
  • 25

1 Answers1

6

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Could you explain to me how this is defined in the standard? Apparently e.g. (C99 6.6/6) describes integer constant expressions, but it doesn't say much about operators. – mooware May 14 '13 at 17:53
  • @mooware: I thought you're asking about C++? C is quite a bit different when it comes to constant expressions (at least C89). I'm happy to let someone else dig up a C reference. – Kerrek SB May 14 '13 at 17:53
  • Yes, I'm asking about C++, but that was the first reference I found here on SO. Sorry for the confusion, and thanks for your answer. – mooware May 14 '13 at 17:56
  • perfect answer to justify Maxim's answer in this post : http://stackoverflow.com/a/7039269/893406 – v.oddou Dec 25 '14 at 02:49