I was wondering why this code snippet compiles and runs
private BusRoute readRouteCursor( final Cursor c )
{
final BusRoute result;
final int count;
if ( c == null || ( count = c.getCount() ) < 1 )
{
result = null;
}
else
{
/*
* Reads cursor
*/
}
return result;
}
I have it working just fine but when I stopped to think about it I wondered why, as the variable count is final but it’s possible for it not to be set if the first condition of the if clause is met.
Does it work because the compiler is clever enough to see there are no uses of count from that point on, and it needn’t be initialised at all?
You’ve answered this question yourself already! As there is no reference to the
countvariable apart from the conditional initialization, no compile error is reported. The error will only appear when you try to reference the variable further in the method body.