Perhaps I am getting rusty (have been writing in Python recently).
Why does this not compile?
if ( (int i=f()) == 0)
without the () around the int i=f() I get another, much more reasonable error of i is not being boolean. But that’s why I wanted the parentheses in the first place!
My guess would be that using the parentheses makes it into an expression, and that declaration statements are not allowed in an expression. Is it so? And if yes, is it one of the C++’s syntax quirks?
BTW, I was actually trying to do this:
if ( (Mymap::iterator it = m.find(name)) != m.end())
return it->second;
You can declare a variable in the
ifstatement in C++ but it is restricted to be used with direct initialization and it needs to convert to a Boolean value:C++ doesn’t have anything which could be described as “declaration expression”, i.e. [sub-] expressions declaring a variable.
Actually, I just looked up the clause in the standard and both forms of initialization are supported according to 6.4 [stmt.select] paragraph 1:
That is, it is also be possible to write:
Obviously, this only works in C++2011 because C++2003 doesn’t have brace-initialization.