Expression “variable, variable = value;”

拈花ヽ惹草 提交于 2019-12-04 03:48:54

问题


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?


回答1:


This is likely an error in the program. The statement

a, b = c;

Is completely equivalent to

b = c;

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!




回答2:


Legal but questionable. The part before the comma doesn't do anything at all.




回答3:


something, somethingElse = 0; 

probably, it is done to avoid the unused variable warning on variable something an to initialize the somethingElse variable to 0.




回答4:


Does this make any sense in C++?

Yes syntactically it does, but without comments you may not know the developers intentions were (if any) other than maybe suppressing a variable warning.

Is a variable name also an expression?

Yes a variable itself is an expression. Ex. if(<expression>) if(something)

This code does compile, so how does this work?

It works by using the comma operator and ignoring the result of something then assigning 0 to somethingElse. Although something was marked volatile 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.



来源:https://stackoverflow.com/questions/9101999/expression-variable-variable-value

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