c++if-statement

When would you want to assign a variable in an if condition?


I recently just lost some time figuring out a bug in my code which was caused by a typo:

if (a=b)

instead of:

if (a==b)

I was wondering if there is any particular case you would want to assign a value to a variable in a if statement, or if not, why doesn't the compiler throw a warning or an error?


Solution

  • if (Derived* derived = dynamic_cast<Derived*>(base)) {
       // do stuff with `derived`
    }
    

    Though this is oft cited as an anti-pattern ("use virtual dispatch!"), sometimes the Derived type has functionality that the Base simply does not (and, consequently, distinct functions), and this is a good way to switch on that semantic difference.