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.
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.
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.
The expressions true == 1 and false == 0 are both true. (And true == 2 is not true).
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.
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.
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 double
s 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With