©1994-2003 Kevin Boone
Home     Section index     K-Zone home C++ tutorial (under construction)

Site search

Glossary
Confused by computer jargon? Look it up!

Shameless plug


Now available!

Articles
- Ten-minute guide to setting up a WAP site

- Talk like your boss: new developments in managerese

More...

Development
File handling in the Linux kernel

Java development for the Sony-Ericsson P800

SunONE Application Server 7 FAQ

More...

Linux
Using Linux with the Treo 600

- Linux on the Tecra M1

- Some notes on openzaurus

More...

Download
Java stuff

Linux stuff

More...

(Please read the download policy)

Home automation
The X10 system

Linux TW723 driver

More...

The K-Zone
K-Zone computing

K-Zone law

K-Zone education and science

K-Zone motorcycles

K-Zone DIY

K-Zone railways

K-Zone martial arts

About the author

K-Zone home page

 
if-then
contents
switch
C++ tutorial: else


'else' is a simple extension to 'if...'
The 'if' instruction allows the program to carry out certain actions if a particular condition is true. Using 'else' you an specify additional actions to be carried out if the condition is not true. The basic structure of the if...else instruction is as follows:

if (condition)
     {
     statement1;
     statement2;
     }
else
     {
     statement3;
     statement4;
     }

Note that the layout of the program statements is designed to show which groups of statements are executed when the condition is true (statements 1 and 2) and which when it is false (statements 3 and 4). Strictly speaking, else is never strictly necessary; we can always provide another 'if' with a different condition. However, there are many common-sense situations where logic of the form 'if (something) then (do something) else (do something else)' is appropriate.

Have a look at the program cin3.cpp. This program asks the user to enter a number. If the number is valid is displayed, otherwise and error message is produced.

The inputting of data is handled by the following two lines:

     float n;
     cin >> n;

Here 'n' is a real-number variable, and data is read into it from the keyboard using 'cin'. If this operation is successful, i.e., the user enters a valid number, then 'cin.good()' will be true:

if (cin.good())...

If it is true, the number is displayed using 'cout'. If not, an error message is produced. The use of '.good()' is a standard and useful way of telling whether the last input or output operation was a success or not. It applies equally well to reading and writing disk files. Technically, '.good()' is an operation or method that is applied to the object 'cin'.