Re:Obscure C++ Features
by bnegreve on Friday April 19, 2013 @02:13PM
(#5577936)
C++ contains a syntactical shorthand for simultaneously declaring a variable and branching on its value.
I think it is a complicated description and a complicated example for saying that the assignment operator (=) returns the value that was assigned.
[ Parent
| on HN ]
If 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.
I see this as no different than being able to do
for (int i = 0; i < len; ++i) { }Imagine 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.
It was added in C99, I think.
It was added in C++ before that.
There 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.Oh, ok I didn't know. So it is indeed a syntactical shorthand for simultaneously declaring a variable and branching.
The 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.
To 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.
The '=' 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.for example int a = b = c = 0;