What If? Declaring variables in if statements, and the curiosities of scope that follows đź”
tl;dr: Variables declared in if statement conditions are accessible in the else statement as well.
Like all good blog posts, this one first came to me while I was banging my head against the keyboard, cursing and screaming out for a maternal figure to hold me while I incoherently babbled about a crash caused by seemingly-nonsensical code.
“This shouldn’t compile! This CAN’T compile!”
And yet, despite the odds, C++ had decided yet again to show me a new side of it. Please take a moment to peruse the following example code, based on the original that caused me such pain, and see if you can spot the bug that causes a nullptr exception.
To save you the trouble, the error is on line 12, where I attempt to access asDerivedA->predicate
.
That’s right: despite declaring asDerivedA
in a separate if statement above, I’m able to access it in an else/if statements below. No, this is not a compiler bug; this is clearly and unambiguously defined in the C++ specification. Before we get to that, let’s take a look at some code.