Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) if

 

if is a keyword to allow conditional program flow:

 

if ( /* condition */ )
{
  //Do this when condition is true
}

 

Optionally, an if statement can be followed by an else statement:

 

if ( /* condition */ )
{
  //Do this when condition is true
  
}
else
{
  //Do this when condition is false
}

 

 

 

 

 

Example

 

#include <iostream>

//Draw a random number
const int x = std::rand();

if (x % 2 == 0)
{
  std::cout << " The value of " << x << " is even." << std::endl;
}
else
{
  std::cout << " The value of " << x << " is odd." << std::endl;
}

 

 

 

 

 

Yoda condition (from The Dodgy Coder

 

When the constant value (for example '6') is put first, so one can be sure that an unintentional assignment (for example 'if (6 = value)') is detected by the compiler.

 

int main()
{
  const int value = 1 + (std::rand() % 6);
  if (6 == value) //A Yoda condition
  {
    //Do something
  }
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict