All C++ programmer know that a variable can be initialized within the definition of a for statement like so:
for (int i = 0; i < 9; ++i) {
std::cout << i << '\n';
}
However, many do not know that the same can be done in an if statement. For example:
if (Foo* f = dynamic_cast<Foo*>(a)) {
f->doSomething();
}
// f is not available here.
You should always define your variables to have the smallest possible scope. This technique allows you to pull your local if variables into the if statement thereby reducing their visibility.
No comments:
Post a Comment