[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppIf

(C++) if

Keyword that checks a condition. If a condition is true, then it performs the statement(s) after if, else it performs the statement(s) after else.

  1. include <iostream>
int main() { //A coin-toss if (rand()%2==0) { std::cout << "You threw head." << std::endl; } else { std::cout << "You threw tail." << std::endl; } return 0; }


The if-statement can be used for debugging by checking certain values. If you do so, check the use of assert, which is an if-statement that can be 'removed' from you code by the preprocessor.

Syntax

This program shows the syntaxes of if and if..else. It also puts wise words on the screen .
  1. include <iostream>
int main() { //Multiple statements using accolades '{' and '}' if (1==2) { for (int i=0; i!=10; ++i) { std::cout << "Life is bad." << std::endl; } } else { for (int i=0; i!=10; ++i) { std::cout << "Life is good." << std::endl; } } //You can skip accolades for a single statement if (1==2) std::cout << "Life is bad." << std::endl; //One statement else std::cout << "Life is good." << std::endl; //One statement //The else condition is not obligatory if (1==2) std::cout << "Life is bad." << std::endl; //One statement std::cout << "Today you should go to the pub." << std::endl; return 0; }


if in debugging

When you use if's for debugging, prefer using either try and catch or assert statements. These both have their own strengths, so see them both.

Code links

'if' links



last edited (November 24, 2006) by bilderbikkel, Number of views: 4690, Current Rev: 11 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.