C++ if Statement

Introduction

To execute a statement or more statements based on some condition, we use the if-statement.

if-statement has the format of:

if (condition) 
   statement 

The statement executes only if the condition is true. Example:

#include <iostream> 

int main() /*from   w w  w  .j a v  a2  s .  c o m*/
{ 
    bool b = true; 
    if (b) 
       std::cout << "The condition is true."; 
} 

To execute multiple statements if the condition is true, we use the block scope {}:

#include <iostream> 

int main() /*from ww w .  j  a va  2 s.  c o  m*/
{ 
    bool b = true; 
    if (b) 
    { 
        std::cout << "This is a first statement."; 
        std::cout << "\nThis is a second statement."; 
    } 
} 

Another form is the if-else statement:

if (condition) 
   statement 
else 
   statement 

If the condition is true, the first statement executes, otherwise the second statement after the else keyword executes.

Example:

#include <iostream> 

int m.ain() /*  w ww. j a va 2  s.  c  o m*/
{ 
    bool b = false; 
    if (b) 
       std::cout << "The condition is true."; 
    else 
       std::cout << "The condition is false."; 
} 

To execute multiple statements in either if or else branch, we use brace-enclosed blocks {}:

#include <iostream> 

int main() /*from w ww . ja v a2 s . co m*/
{ 
    bool b = false; 
    if (b) 
    { 
        std::cout << "The condition is true."; 
        std::cout << "\nThis is the second statement."; 
    } 
    else 
    { 
        std::cout << "The condition is false."; 
        std::cout << "\nThis is the second statement."; 
    } 
} 



PreviousNext

Related