Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 231
Captain Giraffe Avatar asked Jun 26 '12 23:06

Captain Giraffe


People also ask

Is false == false true?

False == (False or True) In this expression python would first solve the comparison operator in bracket. => (False or True) is said to be True. Because the 'OR' operator search for the first truthy value, and if found it returns the value else 'False'. Now we have: =>False == True is False.

Is 2 considered true in C?

The expressions true == 1 and false == 0 are both true. (And true == 2 is not true).

Is it true 0 or 1?

Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.

Is 1 considered true or false?

1 is considered to be true because it is non-zero. The fourth expression assigns a value of 0 to i. 0 is considered to be false.


1 Answers

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!

like image 140
templatetypedef Avatar answered Sep 28 '22 08:09

templatetypedef