C++ if Statement implicit conversion

Introduction

Any literal, object or an expression implicitly convertible to true or false can be used as a condition:

#include <iostream> 

int main() //from  www . j av a 2s .  c o  m
{ 
    if (1) // literal 1 is convertible to true 
    { 
        std::cout << "The condition is true."; 
    } 
} 

If we used an integer variable with a value other than 0, the result would be true:

#include <iostream> 

int main() /* w  w w. j a va  2  s  .  c  o  m*/
{ 
    int x = 10; // if x was 0, the condition would be false 
    if (x) 
    { 
        std::cout << "The condition is true."; 
    } 
    else 
    { 
        std::cout << "The condition is false."; 
    } 
} 

It is good practice to use the code blocks {} inside the if-statement branches, even if there is only one statement to be executed.




PreviousNext

Related