There's no difference between
int * and
map::iterator in that regard. There's a difference in the surrounding semantic constructs that you are using with
int * and
map::iterator, which is why one compiles and other doesn't.
if you have a choice of either
Declaration is not an expression. You can't use a declaration as a subexpression in a larger expression. You cannot use a declaration as a part of explicit comparison, which is exactly what you attempt to do.
For example, if you attempted to do the same thing with
int *, like this
if ((int* x = new int(123)) != NULL)
the code would not not compile for exactly the same reasons your
map::iterator code does not compile.
You have to use
if (int* x = new int(123))
int* x = new int(123);
if (x != NULL)
if ((x = new int(123)) != NULL)
As you can see above,
int * exhibits exactly the same behavior as
In your example, it is impossible to declare
it and perform its comparison with
ifs condition. You will have to use one of the above variants instead, i.e. either
map<string, Property>::iterator it = props.find(PROP_NAME);
if (it != props.end())
map<string, Property>::iterator it;
if ((it = props.find(PROP_NAME)) != props.end())
Choose whichever you like more.
P.S. Of course, formally you can also write
if (map<string, Property>::iterator it = props.find(PROP_NAME))
but it does not do what you want it to do (does not compare the iterator value to
props.end()) and might not compile at all, since the iterator type is probably not convertible to