Search code examples
c++if-statementtype-conversionscopingvariable-declaration

double as true / false


Bjarne suggests using the condition in if's as scope restriction. In particular this example.

if ( double d = fd()  ) {
   // d in scope here...
}

I'm curios how to interpret the declaration in a true / false sense.

  1. It's a declaration
  2. It's a double.

Edit: It's in 6.3.2.1 The C++ programming language as a recommendation.

Edit2: templatetypedefs suggestion of pointers, in particular with dynamic casts, might give insight to Bjarnes suggestion.

SteveJessop tells me: - A condition is not an expression it can also be a declaration, the value used, is the value being evaluated.


Solution

  • The code that you're seeing is a specialized technique for declaring variables in if statements. You commonly see something like this:

    if (T* ptr = function()) {
        /* ptr is non-NULL, do something with it here */
    } else {
        /* ptr is NULL, and moreover is out of scope and can't be used here. */
    }
    

    A particularly common case is the use of dynamic_cast here:

    if (Derived* dPtr = dynamic_cast<Derived*>(basePtr)) {
         /* basePtr really points at a Derived, so use dPtr as a pointer to it. */
    } else {
         /* basePtr doesn't point at a Derived, but we can't use dPtr here anyway. */
    }
    

    What's happening in your case is that you're declaring a double inside the if statement. C++ automatically interprets any nonzero value as true and any zero value as false. What this code means is "declare d and set it equal to fd(). If it is nonzero, then execute the if statement."

    That said, this is a Very Bad Idea because doubles are subject to all sorts of rounding errors that prevent them from being 0 in most cases. This code will almost certainly execute the body of the if statement unless function is very well-behaved.

    Hope this helps!