TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
C++ Coding Standard

Rule:  CFL#011Checked automatically with code checker

Synopsis:The test condition in control statements shall be a non-assignment expression of bool type
Severity Level:9
Category:Control Flow


Use an explicit comparison to make the test condition in a selection or iteration statement of bool type. However, also see [CFL#017].

The test condition in a selection or iteration statement shall not be an assignment expression. This avoids mistaking assignments for comparisons.


bool b = true;
bool c = b;
if (b) // right, see Rec. CFL#017

int i = 123;
if (i)          // wrong: implicit conversion from int to bool
if (i != 0)     // right: expression has bool type
if (i = 123)    // wrong: probably, (i == 123) was intended


Classes that have implemented the "safe bool idiom" (they behave correctly in boolean context) such as is the case for for instance smart pointers and boost::optional won't violate this rule, e.g.

shared_ptr<A> a_sp = someFunctionReturningSharedPtr();
if (a_sp) {     // right: smart pointers are implicitly of boolean type
    cout << a_sp->someData << endl;