82
C + + : T h e C o m p l e t e R e f e r e n c e
} if(x>10) y = 0; declares x and assigns it the value 20. Since this is a true value, the target of the if executes. Variables declared within a conditional statement have their scope limited to the block of code controlled by that statement. Thus, in this case, x is not known outside the if. Frankly, not all programmers believe that declaring variables within conditional statements is good practice, and this technique will not be used in this book.
Jump Statements
C/C++ has four statements that perform an unconditional branch: return, goto, break, and continue. Of these, you may use return and goto anywhere in your program. You may use the break and continue statements in conjunction with any of the loop statements. As discussed earlier in this chapter, you can also use break with switch.
The return Statement
The return statement is used to return from a function. It is categorized as a jump statement because it causes execution to return (jump back) to the point at which the call to the function was made. A return may or may not have a value associated with it. If return has a value associated with it, that value becomes the return value of the function. In C89, a non-void function does not technically have to return a value. If no return value is specified, a garbage value is returned. However, in C++ (and in C99), a non-void function must return a value. That is, in C++, if a function is specified as returning a value, any return statement within it must have a value associated with it.
(Even in C89, if a function is declared as returning a value, it is good practice to actually return one!)
The general form of the return statement is return expression;
The expression is present only if the function is declared as returning a value. In this case, the value of expression will become the return value of the function.
You can use as many return statements as you like within a function. However, the function will stop executing as soon as it encounters the first return. The } that ends a function also causes the function to return. It is the same as a return without any specified value. If this occurs within a non-void function, then the return value of the function is undefined.
A function declared as void may not contain a return statement that specifies a value. Since a void function has no return value, it makes sense that no return statement within a void function can return a value.
See Chapter 6 for more information on return.
C h a p t e r 3 : S t a t e m e n t s
83
The goto Statement
Since C/C++ has a rich set of control structures and allows additional control using
break
and continue, there is little need for goto. Most programmers' chief concern about the goto is its tendency to render programs unreadable. Nevertheless, although the goto statement fell out of favor some years ago, it occasionally has its uses. There are no programming situations that require goto. Rather, it is a convenience, which, if used wisely, can be a benefit in a narrow set of programming situations, such as jumping out of a set of deeply nested loops. The goto is not used outside of this section.
The goto statement requires a label for operation. (A label is a valid identifier followed by a colon.) Furthermore, the label must be in the same function as the goto that uses it—you cannot jump between functions. The general form of the goto statement is
.
.
.
goto label;
label: where label is any valid label either before or after goto. For example, you could create a loop from 1 to 100 using the goto and a label, as shown here: x = 1; loop1: x++; if(x<100) goto loop1;
The break Statement
The break statement has two uses. You can use it to terminate a case in the switch statement (covered in the section on switch earlier in this chapter). You can also use it to force immediate termination of a loop, bypassing the normal loop conditional test.
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. For example,
#include <stdio.h> int main(void)
{ int t;
84
C + + : T h e C o m p l e t e R e f e r e n c e for(t=0; t<100; t++) { printf("%d ", t); if(t==10) break;
}
} return 0; prints the numbers 0 through 10 on the screen. Then the loop terminates because break causes immediate exit from the loop, overriding the conditional test t<100.
Programmers often use the break statement in loops in which a special condition can cause immediate termination. For example, here a keypress can stop the execution of the look_up( ) function: void look_up(char *name)
{ do {
/* look up names ... */ if(kbhit()) break;
} while(!found);
/* process match */
}
The kbhit( ) function returns 0 if you do not press a key. Otherwise, it returns a nonzero value. Because of the wide differences between computing environments, neither Standard C nor Standard C++ defines kbhit( ), but you will almost certainly have it (or one with a slightly different name) supplied with your compiler.
A break causes an exit from only the innermost loop. For example, for(t=0; t<100; ++t) { count = 1; for(;;) { printf("%d ", count); count++; if(count==10) break;
}
} prints the numbers 1 through 10 on the screen 100 times. Each time execution encounters
break
, control is passed back to the outer for loop.
C h a p t e r 3 : S t a t e m e n t s
85
A break used in a switch statement will affect only that switch. It does not affect any loop the switch happens to be in.
The exit( ) Function
Although exit( ) is not a program control statement, a short digression that discusses it is in order at this time. Just as you can break out of a loop, you can break out of a program by using the standard library function exit( ). This function causes immediate termination of the entire program, forcing a return to the operating system. In effect, the exit( ) function acts as if it were breaking out of the entire program.
The general form of the exit( ) function is void exit(int return_code);
The value of return_code is returned to the calling process, which is usually the operating system. Zero is generally used as a return code to indicate normal program termination.
Other arguments are used to indicate some sort of error. You can also use the macros
EXIT_SUCCESS
and EXIT_FAILURE for the return_code. The exit( ) function requires the header stdlib.h. A C++ program may also use the C++-style header <cstdlib>.
Programmers frequently use exit( ) when a mandatory condition for program execution is not satisfied. For example, imagine a virtual reality computer game that requires a special graphics adapter. The main( ) function of this game might look like this:
#include <stdlib.h> int main(void)
{ if(!virtual_graphics()) exit(1); play();
/* ... */
}
/* .... */ where virtual_graphics( ) is a user-defined function that returns true if the virtual-reality graphics adapter is present. If the adapter is not in the system, virtual_graphics( ) returns false and the program terminates.
As another example, this version of menu( ) uses exit( ) to quit the program and return to the operating system: void menu(void)
{
86
C + + : T h e C o m p l e t e R e f e r e n c e char ch; printf("1. Check Spelling\n"); printf("2. Correct Spelling Errors\n"); printf("3. Display Spelling Errors\n"); printf("4. Quit\n"); printf(" Enter your choice: "); do { ch = getchar(); /* read the selection from the keyboard */ switch(ch) { case '1': check_spelling(); break; case '2': correct_errors(); break; case '3': display_errors(); break; case '4': exit(0); /* return to OS */
}
} while(ch!='1' && ch!='2' && ch!='3');
}
The continue Statement
The continue statement works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the while and do-while loops, program control passes to the conditional tests. For example, the following program counts the number of spaces contained in the string entered by the user:
/* Count spaces */
#include <stdio.h> int main(void)
{
C h a p t e r 3 : S t a t e m e n t s
87 char s[80], *str; int space; printf("Enter a string: "); gets(s); str = s; for(space=0; *str; str++) { if(*str != ' ') continue; space++;
} printf("%d spaces\n", space);
} return 0;
Each character is tested to see if it is a space. If it is not, the continue statement forces the for to iterate again. If the character is a space, space is incremented.
The following example shows how you can use continue to expedite the exit from a loop by forcing the conditional test to be performed sooner: void code(void)
{ char done, ch;
} done = 0; while(!done) { ch = getchar(); if(ch=='$') { done = 1; continue;
} putchar(ch+1); /* shift the alphabet one position higher */
}
This function codes a message by shifting all characters you type one letter higher. For example, an A becomes a B. The function will terminate when you type a $. After a $ has been input, no further output will occur because the conditional test, brought into effect by continue, will find done to be true and will cause the loop to exit.