|
©1994-2003 Kevin Boone |
| Home Section index K-Zone home | C++ tutorial (under construction) |
|
Make simple decisions using 'if...' The simplest branching operation in C/C++ is the 'if' statement. This allows the program to execute a particular set of statements if some condition is true. The general form of an 'if' statement is:
if (condition)
{
statement1;
statement2;
// ...more statements
}
The statements to be executed if the condition is true are grouped together in the curly braces. If there is only one statement, you don't need the curly braces; the general form of the branch is then very simple:
if (condition)
statement;
Note that there is no need for the word 'then' as there is in some other languages. The 'condition' is any test that might be true or false. Here are some examples:
if ( x < 0 )
{
//Do this section if 'x' is less than zero
}
if ( MenuSelection == Exit )
{
//User selected 'Exit' from the menu
}
if ( cin.good() )
{
//Last input operation was a success...
}
For more information about the types of comparison that can be made, see 'Operators' in the reference section.
In C/C++, '==' means 'is equal to?'
x == 100;
this is not an error! In fact, this line of program does absolutely nothing!
In C/C++, '!=' means 'is not equal to?'
if (x != y) // ... means: execute the following statement if 'x' is not equal to 'y'.
In C/C++, '0' is the same as 'false'
if (x) // ... meaning: exectute the following statement if x is not zero. Personally, I would not write a line like this; I would always state explicity what is meant:
if (x != 0) // ...
Boolean variables store the results of tests
bool Ready = false;
// ...
Ready = true;
// ...
if (Ready == true)
{
// ...
}
In the first line the variable 'Ready' is set to 'false'. Later in the program the variable is used in an 'if' statement. It would equally correct to write
if (Ready)
{
// ...
}
In practice boolean variables are not that widely used, as integer variables can be used in exactly the same way, and many programmers got used to doing this in C, which does not have a boolean data type.
|