5 ms·
C++ contains a syntactical shorthand for simultaneously declaring a variable and branching on its value. if (MouseEvent *mouse = dynamic_cast<MouseEvent *>
by bnegreve 14y ago
C++ contains a syntactical shorthand for simultaneously declaring a variable and branching on its value.
if (MouseEvent *mouse = dynamic_cast<MouseEvent *>(event))
I think it is a complicated description and a complicated example for saying that the assignment operator (=) returns the value that was assigned.
- jomar 14y agoIf this were just if (mouse = dynamic_cast<MouseEvent *>(event)) then it would indeed just be an if condition expression that happened to be an assignment. But the variable is being declared as well, so what's actually going on here is a declaration and an initialiser expression. There is actually new functionality here that needed a bit of language design thought, e.g., the declared variable's scope is the whole if statement, not just the condition expression.
- kelnos 14y agoI see this as no different than being able to do for (int i = 0; i < len; ++i) { }
- axusgrad 14y agoImagine my surprise, getting out of college and trying to use this at my job, when the compiler told me it was invalid! It wasn't obscure to me, but apparently was to the Sun Studio C++ compiler.
- minasss 14y agofor example int a = b = c = 0;
- danbruc 14y agoIt is more like int a = int b = int c = 0;
- ben0x539 14y agoThe noteworthy bit is that declarations are valid in the conditional "expression" of if-statements and evaluate to the declared variable. It's imo not obvious that declarations are expressions sometimes.
- deleted 14y ago[deleted]
- deleted 14y ago[deleted]
- Sharlin 14y agoTo be precise, declarations are never expressions - there are two forms of if and while statements in the grammar, one taking an expression and the other a declaration.
- Ives 14y agoThere are some problems with that method though. If, for example, you'd like to reverse the condition, you can't write if (!(MouseEvent *mouse = dynamic_cast<MouseEvent *>(event))) {} because a definition is not a general expression, but was only added as an "extra" to allow its use in some cases in conditionals.
- bnegreve 14y agoOh, ok I didn't know. So it is indeed a syntactical shorthand for simultaneously declaring a variable and branching.
- Sharlin 14y agoThe '=' above is not an assignment operator, as there is no assigment, it is a declaration. Yes, the following is also valid: MouseEvent *mouse; if(mouse = dynamic_cast<MouseEvent *>(event))) but it is not the same thing.