With such a simple condition, you could just use the ternary operator:
const QList<Type> zoneList = invar ? invar->getZones() : aList;
If the initialization gets more complex than that and you happen to use C++11, then you can use a new idiom made possible by lambdas:
const QList<Type> zoneList = [] () -> QList<Type> {
// ^^ possibly [&] to capture variables
// some complex stuff that returns a QList<Type>
}(); // Note the () that calls the lambda immediately
If you are stuck with C++03 (or, Stroustrup forbid, C++98), there are few solutions left except calling another function/method, with the drawback that you have to pass as a parameter any local variable you need to compute the const value.
Edit: I realize I haven't fully answered your question. Others have already explained that your first if
can't work because it's a matter of scope, I won't add much except that adding braces will probably make it clearer for you (note how this is strictly the same code as yours: the braces are optional when the if
/else
bodies are just a single statement but their presence/absence doesn't change the semantics of the code):
if (invar) {
const QList<Type> zoneList = invar->getZones();
}
else {
const QList<Type> zoneList = aList;
}