表达式“变量,变量=值”
我一直在查看一些 MFC 代码,发现了这个表达式。它在 OnInitDialog() 函数中,看起来不是 MFC 特定的。这些变量有一些名称,值为 0。
int volatile something, somethingElse; //this was global
something, somethingElse = 0; //this was inside the function
这在 C++ 中有意义吗?我知道逗号运算符是如何工作的,尽管在像这里这样的自由形式中它应该分隔表达式。变量名也是表达式吗?这段代码确实可以编译,那么它是如何工作的呢?
I have been looking through some MFC code and i came across this expression. It was in OnInitDialog() function, didn't look like it's MFC specific. The variables had some name, value was 0.
int volatile something, somethingElse; //this was global
something, somethingElse = 0; //this was inside the function
Does this make any sense in C++? I know how the comma operator works, though in a free form like here it should be separating expressions. Is a variable name also an expression? This code does compile, so how does this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这很可能是程序中的错误。该语句
完全相当于
Since 逗号运算符从左到右计算并丢弃除最后一个值之外的所有值。由于表达式 a 没有副作用,因此它本质上是一个空操作。
我怀疑这要么是程序员错误,要么是代码从不同语言到 C++ 的错误翻译。您应该联系作者让他们知道这一点。
希望这有帮助!
This is likely an error in the program. The statement
Is completely equivalent to
Since the comma operator evaluates from left to right and discards all values except the last. Since the expression a has no side effects, it's essentially a no-op.
I would suspect that this is either programmer error or an incorrect translation of code from a different language into C++. You should contact the author to let them know about this.
Hope this helps!
合法但值得怀疑。逗号之前的部分根本不执行任何操作。
Legal but questionable. The part before the comma doesn't do anything at all.
这样做可能是为了避免变量
something
上出现未使用的变量警告,并将somethingElse
变量初始化为0
。probably, it is done to avoid the unused variable warning on variable
somethin
g an to initialize thesomethingElse
variable to0
.是的,从语法上来说确实如此,但是如果没有注释,您可能不知道开发人员的意图(如果有的话)除了可能抑制变量警告之外。
是的,变量本身就是一个表达式。前任。
if(<表达式>) if(某事)
它的工作原理是使用 逗号运算符 并忽略
something
的结果将 0 分配给somethingElse
。尽管某物
被标记为易失性
,但原始开发人员可能拥有一个仍然抱怨未使用变量的编译器,并且作为聪明的开发人员,他或她随后决定使用该语法来抑制。Yes syntactically it does, but without comments you may not know the developers intentions were (if any) other than maybe suppressing a variable warning.
Yes a variable itself is an expression. Ex.
if(<expression>) if(something)
It works by using the comma operator and ignoring the result of
something
then assigning 0 tosomethingElse
. Althoughsomething
was markedvolatile
the original developer may of had a compiler that still complained about unused variables and being the clever developer he or she was then decided to suppress with that syntax.