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.
- It’s a declaration
- 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.
The code that you’re seeing is a specialized technique for declaring variables in
ifstatements. You commonly see something like this:A particularly common case is the use of
dynamic_casthere:What’s happening in your case is that you’re declaring a
doubleinside theifstatement. C++ automatically interprets any nonzero value astrueand any zero value asfalse. What this code means is “declaredand set it equal tofd(). If it is nonzero, then execute theifstatement.”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 theifstatement unlessfunctionis very well-behaved.Hope this helps!