next up previous
Next: Examples of if statements Up: Introduction to C++ Programming Previous: Review Questions


The if statement

As remarked in section 5.2, in order to produce algorithms, it must be possible to select the next statement to execute on the basis of some condition. Simple conditions have been covered in Lesson 10. The if statement is the simplest form of conditional or selection statement in C++. The following if statement

if (x > 0.0)
   cout << "The value of x is positive";
will print out the message ` The value of x is positive' if x is positive.

The general form of the if statement is:

if (condition)
statement
where condition is any valid logical expression as described in Lesson 10.1 or a bool variable. The statement can be a single C++ statement of any kind and must be terminated by a semi-colon. It can also be a compound statement, which is a sequence of statements enclosed in left and right braces and acts as a single statement. The closing right brace is not followed by a semi-colon.



Subsections
next up previous
Next: Examples of if statements Up: Introduction to C++ Programming Previous: Review Questions
Peter JB King
1999-08-31