The expression "variable, variable = value;"

I was looking at the MFC code and I came across this expression. It was in the OnInitDialog () function, not like MFC. The variables had some name, the value is 0.

int volatile something, somethingElse; //this was global something, somethingElse = 0; //this was inside the function 

Does this make sense in C ++? I know how the comma operator works, although in free form, like here, it should separate expressions. Is the variable name also an expression? This code compiles, so how does it work?

+4
source share
4 answers

This is probably a bug in the program. Statement

 a, b = c; 

Fully equivalent

 b = c; 

Since the comma operator evaluates from left to right and discards all values ​​except the last one. Since expression a has no side effects, it is essentially not an operator.

I would suspect that this is either a programmer’s mistake or an incorrect translation of code from another language in C ++. You must contact the author to report it.

Hope this helps!

+6
source

Legal, but controversial. The part before the comma does nothing.

+4
source

Does this make sense in C ++?

Yes, it does it syntactically, but without comment you may not know what the intentions of the developers were (if any), except perhaps suppressing the warning variable.

Is the variable name also an expression?

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

This code compiles, so how does it work?

It works with a comma operator and ignores the result of something , and then assigns 0 to somethingElse . Although something was marked volatile , the original developer might have a compiler that still complained about unused variables and was a smart developer, which was then resolved to suppress with this syntax.

+4
source
 something, somethingElse = 0; 

perhaps this is done to avoid warning an unused variable in somethin g an variable to initialize somethingElse to 0 .

+4
source

Source: https://habr.com/ru/post/1394255/


All Articles