Is the comma operator allowed in a constant-expression in C++11?

半腔热情 提交于 2019-11-30 08:05:20
  1. Yes, I believe this is a change between C++03 and C++11. I believe it was done for roughly the reason to which you allude -- that there's no particularly good reason a comma operator can't be part of a constant expression.

  2. I believe the rule in C++03 originated from the rule in C (C90, §6.4):

Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within the operand of a sizeof operator.

As to why the comma operator was prohibited in constant expressions in C, I can only speculate. My immediate guess would be to assure that a definition like:

int x[2, 5];

...would be rejected instead of leaving the user with the mistaken belief that he'd defined a 2x5 element array, when (if a comma operator were allowed there) he'd really defined x with only 5 elements.

However, it must be said that even the following program compiles fine with the -std=c++03 option (both on Clang and GCC), which is clearly not correct, given the above quote from the C++03 Standard

Not so fast. You need to also use -pedantic (or -pedantic-errors) to get Clang and GCC to strictly enforce the C++03 rules. With that, GCC trunk says:

<stdin>:1:16: error: array bound is not an integer constant before ‘]’ token

and Clang trunk says:

<stdin>:1:19: error: variable length arrays are a C99 feature [-Werror,-Wvla-extension]
void f() { int arr[(0, 42)]; }
                  ^

As you note, this code is valid C++11. However, top-level commas are still not valid in C++11, because a constant-expression in the C++11 grammar is a kind of conditional-expression (where a top-level comma is not permitted). Thus:

int arr[0, 42];

is still ill-formed.

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