是“int i = x++, j = x++;”吗?合法的?
我认为标题已经说得很清楚了。我对此并不完全确定,而且我无法通过谷歌找到一个好的答案(唉,我还没有致力于标准符的艺术),所以我问:
int i = x++, j = x++;
这是定义的吗? 我非常确定 i = x++, j = x++;
作为普通语句将是未定义的行为 是逗号运算符,它是序列点并且是合法的,但是没有来源非常清楚初始化程序是否以分号结束或一旦开始声明下一个变量,并且由于这不是正在使用的逗号运算符,所以我找不到明确的答案。因此,要么 a) 逗号结束初始化程序,是一个序列点,并且有效,要么 b) 无效。是哪一个?
为了排除这种情况,我知道我应该简化这个令人头疼的问题,并将其写为:
int i = x++;
int j = x++;
并保证它已定义。我出于好奇而询问更多。
Pretty clear in the title, I think. I'm not entirely sure on this, and I can't find a good answer via the Googles (alas, I haven't committed to the fine art of standards-fu), so I ask:
int i = x++, j = x++;
Is this defined? I am quite sure that i = x++, j = x++;
as a normal statement would be undefined behavior is the comma operator, which is a sequence point and would be legal, but no source is quite clear on whether an initializer ends at the semicolon or once the next variable starts being declared, and since that's not the comma operator in use I can't find a clear answer. So either a) the comma ends the initializer, is a sequence point, and that works, or b) it doesn't. Which is it?
And to preclude, I know I should simplify the headache and just write it as:
int i = x++;
int j = x++;
And guarantee that it's defined. I'm asking more out of curiosity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
初始化程序的末尾是一个序列点,因此标题中的示例是合法的。
逗号运算符也是一个序列点,因此您的“正常语句”也是合法且定义良好的。
维基百科文章有 C 和 C++ 序列点的列表。
跟进下面的评论,这里展示了逗号运算符的强大功能,保留在 FreeBSD 的 stdio.h 中(在
ifndef __GNUC__
下):The end of an initializer is a sequence point so the example in the title is legal.
The comma operator is also a sequence point so that your "normal statement" is also legal and well-defined.
The wikipedia article has a list of the C and C++ sequence points.
To follow up on a comment below, here's a demonstration of the fearsome power of the comma operator, as preserved in FreeBSD's stdio.h (under
ifndef __GNUC__
):这是一个棘手的问题。
如果你写了:
我说过:它是未定义的。 (各种 C 和 C++ 标准保持未定义)
但在初始化程序中我不确定;D ofc 我得出的结论是它也未定义,但谁知道......
Angelo
Thats a tricky question.
If you had written:
I had said: it is undefined. (Various C and C++ standards keep that undfined)
But in an initializer I'm not sure ;D ofc I had concluded it is there undefined as well, but who knows ...
Angelo