Prev Next

Control Structures

Conditionals

If statements

Conditionals are used for making decisions. The most frequently used conditional is the if-statement. It has the form

if (condition) statement else statement

The first statement is done if the condition is true, and the second is done if the condition is false. The else part is optional. If it is omitted, then nothing is done when the condition is false. Typically, the statements are compound statements. Here is an example.

  if(x == 0) {
     y = 0;
  }
  else {
    y = 1/x;  
  }
The parentheses around the condition are required.

Caution: The condition being tested is any integer or pointer expression. If the condition has value 0 (or NULL), then it is considered to be false. If the condition has any nonzero value, then it is considered to be true. This can be confusing. For example, cin.fail is a function that will tell you whether the most recent operation on cin failed. In C/C++, a function is represented by the address where the machine-language code of the function is loaded. Since an address is a pointer, a function is a pointer. If you write

  if(cin.fail) {
    ...
  }
you are not running function cin.fail at all, but are asking whether the pointer cin.fail is not null. Of course, it is not. The correct way to ask whether the most recent operation on cin failed is
  if(cin.fail()) {
    ...
  }

Comparisons and boolean operators

Here are some operations for creating conditions.

OperatorPurpose
== equality test
= inequality test
> test for greater
< test for less
>= test for greater or equal
<= test for less or equal
&& 'and'. Expression A && B has value 1 if both A and B are nonzero, and has value 0 if either A or B is 0. In the case where A is 0, expression B is not evaluated.
| | 'or'. Expression A | | B is 0 if both A and B are 0, and is 1 otherwise. In the case where A is nonzero, expression B is not evaluated.
! 'not'. Expression !A is 0 if A is nonzero, and is 1 if A is 0.

Caution: You can use the comparison operations on pointers. They compare addresses. For example, if p and q each have type char*, then testing whether p == q will test whether p and q are the same pointer. It will not test whether the strings pointed to by p and q are the same.

Caution: A frequent error is to confuse = and ==. If you write

  if(x = y) ...
then you will not get a test to see if x and y have the same value. Instead, you will get an assignment, putting the value of y into x, and that value will be tested. This is a serious error. You should learn to check your program carefully for this. One way to avoid this problem is, when doing a comparison that involves a constant, to write the constant first. That way, if you accidentally write = instead of == you will get a compile error. For example, write
  if(0 == x) ...

Conditional expressions

You can make a test in an expression in C/C++. Expression

  condition ? val1 : val2

is equal to val1 if condition is nonzero, a nd is val2 if condition is 0. For example, expression

x > y ? x : y
evaluates to the larger of x and y.

Switches

Sometimes you want to make several tests of a single value. C/C++ provides a switch statement for that purpose. Here is an example.

switch (x) {
  case -1: 
    printf("Less than zero\n");
    break;

  case 0:
    printf("Equal to 0\n");
    break;

  case 1:
    printf("Greater than 0\n");
    break;

  default:
    printf("Not one of the things I know about\n");
}

Caution: You must include break; after each case. If you do not, then the program will keep going into the next case. For example, if you run the following with day = 5

switch(day) {
  case 5: 
    printf("five gold rings\n");
  case 4: 
    printf("four calling birds\n"); 
  case 3: 
    printf("three french hens\n"); 
  case 2: 
    printf("two turtledoves\n"); 
  case 1: 
    printf("and a partridge in a pear tree\n"); 
} 
the program prints
five gold rings
four calling birds
three french hens
two turtledoves
and a partridge in a pear tree

Note: If there is no default case, then nothing is done if none of the cases match.

Note: You can have two or more cases do the same thing. Just put them in a row, as in

  case 4:
  case 5:
    text for these cases

Note: You can only use a switch when the type of the value being tested is an integer type.

Loops

C/C++ provides three kinds of loop.

While loops

A while-loop is used to do a statement zero or more times. Statement

while (condition) statement

does the statement (called the loop body) repeatedly until the loop top is reached , condition is tested and found to be false (zero). For example, suppose that s is a pointer to a null-terminated string. The following sets n to the length of string s.

  char* p = s;
  n = 0;
  while(*p != 0) {
    p++;
    n++;
  }
The condition is tested before the loop is entered for the first time. If the condition is zero immediately, then the loop body is not performed at all.

Do loops

A do-loop is used to do a statement one or more times. Statement

do statement while (condition);

does the statement repeatedly until the condition is true (nonzero), but tests the condition for the first time only after it has already done the statement once.

For loops

A for-loop is typically used to count through a fixed sequence of values. In general, statement

for(A; B; C) statement

abbreviates

  A;
  while (B) {
    statement
    C;
  }

For example, here is a statement that prints the numbers from 0 to 9.

  for(i = 0; i < 9; i++) {
    cout << i << endl;
  }
This for-loop abbreviates
  i = 0;
  while(i < 9) {
    cout << i << endl;
    i++
  }

Note: A for-loop has just three parts, separated by semicolons, within its parentheses. You can omit any part, but must not omit the semicolons. If you omit the test (the middle part), you get an infinite loop.

Note: In C++, you can declare variables within the parentheses after for (in the A part). Those variables are only available within the for-loop. They are not available outside the loop. For example,

  for(int i = 0; i < 10; i++) {
    ...
  }
  if(i < 10) ...
is not allowed because i is local to the for loop.

Breaking and continuing loops

In any kind of loop you can include the following two statements.

StatementMeaning
break; Exit the loop immediately. Proceed just after the loop.
continue; Go back to the top of the loop immediately and start the next iteration. In the case of a for loop, perform the update action (the C part) before starting the next iteration.


Prev Next