PS-Trainer C - Entwicklung
Programm - Flusskontrolle: Verzweigungen
Homepage von PS-Trainer - C-Entwicklung - Flusskontrolle - an PS-Trainer
PS-Trainer PS-Trainer

Program Flow Control  
if Statement The if statement controls conditional branching
Conditional-Expression Operator (? :) The conditional operator (? :) is a ternary operator (it takes three operands).
switch Statement The C++ switch statement allows selection among multiple sections of code, depending on the value of an expression.
break Statement The break statement is used to exit an iteration or switch statement.
goto Statement The goto statement transfers (unconditional) control to a label.


if Statement
The if statement controls conditional branching.
The body of an if statement is executed if the value of the expression is nonzero.
The syntax for the if statement has two forms.

Syntax
selection-statement :
if ( expression ) statement
if ( expression ) statement else statement
In both forms of the if statement, the expressions, which can have any value except a structure, are evaluated, including all side effects.

In the first form of the syntax, if expression is true (nonzero), statement is executed. If expression is false (zero), statement is ignored. In the second form of syntax, which uses else, the second statement is executed if expression is false. With both forms, control then passes from the if statement to the next statement in the program unless one of the statements contains a break, continue, or goto.

The following are examples of the if statement:
if ( i > 0 )
y = x / i;
else
{
x = i;
y = f( x );
}

In this example, the statement y = x/i; is executed if i is greater than 0. If i is less than or equal to 0, i is assigned to x and f( x ) is assigned to y. Note that the statement forming the if clause ends with a semicolon.

When nesting if statements and else clauses, use braces {...} to group the statements and clauses into compound statements that clarify your intent. If no braces are present, the compiler resolves ambiguities by associating each else with the closest if that lacks an else.
if ( i > 0 ) /* Without braces */
if ( j > i )
x = j;
else
x = i;


The else clause is associated with the inner if statement in this example. If i is less than or equal to 0, no value is assigned to x.
if ( i > 0 )
{ /* With braces */
if ( j > i )
x = j;
}
else
x = i;

The braces surrounding the inner if statement in this example make the else clause part of the outer if statement. If i is less than or equal to 0, i is assigned to x.
Many programmers use curly braces ({ }) to explicitly clarify the pairing of complicated if and else clauses. Although the braces are not strictly necessary, they clarify the pairing between if and else statements.


Conditional-Expression Operator
C has one ternary operator: the conditional-expression operator (? :).
Syntax
conditional-expression :
logical-OR-expression
logical-OR-expression ? expression : conditional-expression

The logical-OR-expression must have integral, floating, or pointer type. It is evaluated in terms of its equivalence to 0.
A sequence point follows logical-OR-expression.

Evaluation of the operands proceeds as follows:
If logical-OR-expression is not equal to 0, expression is evaluated. The result of evaluating the expression is given by the nonterminal expression. (This means expression is evaluated only if logical-OR-expression is true.)
If logical-OR-expression equals 0, conditional-expression is evaluated. The result of the expression is the value of conditional-expression. (This means conditional-expression is evaluated only if logical-OR-expression is false.)
Note that either expression or conditional-expression is evaluated, but not both.

The type of the result of a conditional operation depends on the type of the expression or conditional-expression operand, as follows:
If expression or conditional-expression has integral or floating type (their types can be different), the operator performs the usual arithmetic conversions. The type of the result is the type of the operands after conversion.
If both expression and conditional-expression have the same structure, union, or pointer type, the type of the result is the same structure, union, or pointer type.
If both operands have type void, the result has type void.
If either operand is a pointer to an object of any type, and the other operand is a pointer to void, the pointer to the object is converted to a pointer to void and the result is a pointer to void.
If either expression or conditional-expression is a pointer and the other operand is a constant expression with the value 0, the type of the result is the pointer type.
In the type comparison for pointers, any type qualifiers (const or volatile) in the type to which the pointer points are insignificant, but the result type inherits the qualifiers from both components of the conditional.
Expressions with the Conditional Operator
The conditional operator (? :) is a ternary operator (it takes three operands).
The conditional operator works as follows:
The first operand is evaluated and all side effects are completed before continuing.
If the first operand evaluates to true (a nonzero value), the second operand is evaluated.
If the first operand evaluates to false (0), the third operand is evaluated.

The result of the conditional operator is the result of whichever operand is evaluated — the second or the third.
Only one of the last two operands is evaluated in a conditional expression.

Example:
(val >= 0) ? val : -val
If the condition is true, the expression evaluates to val. If not, the expression equals –val.


switch Statement
The C++ switch statement allows selection among multiple sections of code, depending on the value of an expression.

The expression enclosed in parentheses, the "controlling expression," must be of an integral type or of a class type for which there is an unambiguous conversion to integral type. Integral promotion is performed as described in Integral Promotions.

The switch statement causes an unconditional jump to, into, or past the statement that is the "switch body," depending on the value of the controlling expression, the values of the case labels, and the presence or absence of a default label. The switch body is normally a compound statement (although this is not a syntactic requirement). Usually, some of the statements in the switch body are labeled with case labels or with the default label. Labeled statements are not syntactic requirements, but the switch statement is meaningless without them. The default label can appear only once.

Syntax
case constant-expression : statement
default : statement

The constant-expression in the case label is converted to the type of the controlling expression and is then compared for equality. In a given switch statement, no two constant expressions in case statements can evaluate to the same value. The behavior is shown in the table below.

Switch Statement Behavior
Condition Action
Converted value matches that of the promoted controlling expression Control is transferred to the statement following that label.
None of the constants match the constants in the case labels; default label is present. Control is transferred to the default label.
None of the constants match the constants in the case labels; default label is not present. Control is transferred to the statement after the switch statement.

An inner block of a switch statement can contain definitions with initializations as long as they are reachable — that is, not bypassed by all possible execution paths. Names introduced using these declarations have local scope. The following code fragment shows how the switch statement works:

switch( tolower( *argv[1] ) )
{
// Error. Unreachable declaration.
char szChEntered[] = "Character entered was: ";

case 'a' :
{
// Declaration of szChEntered OK. Local scope.
char szChEntered[] = "Character entered was: ";
cout << szChEntered << "a\n";
}
break;

case 'b' :
// Value of szChEntered undefined.
cout << szChEntered << "b\n";
break;

default:
// Value of szChEntered undefined.
cout << szChEntered << "neither a nor b\n";
break;
}

Nesting: A switch statement can be nested. In such cases, case or default labels associate with the most deeply nested switch statements that enclose them.
For example:
switch( msg )
{
case WM_COMMAND: // Windows command. Find out more.
switch( wParam )
{
case IDM_F_NEW: // File New menu command.
delete wfile;
wfile = new WinAppFile;
break;
case IDM_F_OPEN: // File Open menu command.
wfile->FileOpenDlg();
break;
...
}
case WM_CREATE: // Create window.
...
break;
case WM_PAINT: // Window needs repainting.
...
break;
default:
return DefWindowProc( hWnd, Message, wParam, lParam );
}

The preceding code fragment from a message loop shows how switch statements can be nested. The switch statement that selects on the value of wParam is executed only if msg is WM_COMMAND. The case labels for menu selections, IDM_F_NEW and IDM_F_OPEN, associate with the inner switch statement.

Drop through: Control is not impeded by case or default labels. To stop execution at the end of a part of the compound statement, insert a break statement. This transfers control to the statement after the switch statement.
This example demonstrates how control "drops through" unless a break statement is used:
BOOL fClosing = FALSE;

...

switch( wParam )
{
case IDM_F_CLOSE: // File close command.
fClosing = TRUE;
// fall through

case IDM_F_SAVE: // File save command.
if( document->IsDirty() )
if( document->Name() == "UNTITLED" )
FileSaveAs( document );
else
FileSave( document );

if( fClosing )
document->Close();

break;
}

The preceding code shows how to take advantage of the fact that case labels do not impede the flow of control. If the switch statement transfers control to IDM_F_SAVE, fClosing is FALSE. Therefore, after the file is saved, the document is not closed. However, if the switch statement transfers control to IDM_F_CLOSE, fClosing is set to TRUE, and the code to save a file is executed.


break Statement
The break statement is used to exit an iteration or switch statement.

It transfers control to the statement immediately following the iteration substatement or switch statement.
The break statement terminates only the most tightly enclosing loop or switch statement. In loops, break is used to terminate before the termination criteria evaluate to 0. In the switch statement, break is used to terminate sections of code — normally before a case label.

Note There are other simple ways to escape a loop. It is best to use the break statement in more complex loops, where it can be difficult to tell whether the loop should be terminated before several statements have been executed.
For an example of using the break statement within the body of a switch statement, see the switch Statement.
The following example illustrates the use of the break statement in a for loop:
for( ; ; ) // No termination condition.
{
if( List->AtEnd() )
break;
List->Next();
}
cout << "Control transfers to here.\n";

continue Statement
The continue statement forces immediate transfer of control to the loop-continuation statement of the smallest enclosing loop. (The "loop-continuation" is the statement that contains the controlling expression for the loop.) Therefore, the continue statement can appear only in the dependent statement of an iteration statement (although it may be the sole statement in that statement). In a for loop, execution of a continue statement causes evaluation of expression2 and then expression1.
The following example shows how the continue statement can be used to bypass sections of code and skip to the next iteration of a loop:
#include <conio.h>

// Get a character that is a member of the zero-terminated
// string, szLegalString. Return the index of the character
// entered.
int GetLegalChar( char *szLegalString )
{
char *pch;

do
{
char ch = _getch();

// Use strchr library function to determine if the
// character read is in the string. If not, use the
// continue statement to bypass the rest of the
// statements in the loop.
if( (pch = strchr( szLegalString, ch )) == NULL )
continue;

// A character that was in the string szLegalString
// was entered. Return its index.
return (pch - szLegalString);

// The continue statement transfers control to here.
} while( 1 );

return 0;
}


goto Statement
The goto statement transfers control to a label.
The given label must reside in the same function and can appear before only one statement in the same function.

Syntax
statement :
labeled-statement
jump-statement
jump-statement :

goto identifier ;
labeled-statement :
identifier : statement


A statement label is meaningful only to a goto statement; in any other context, a labeled statement is executed without regard to the label.
A jump-statement must reside in the same function and can appear before only one statement in the same function. The set of identifier names following a goto has its own name space so the names do not interfere with other identifiers. Labels cannot be redeclared. See Name Spaces for more information.

It is good programming style to use the break, continue, and return statement in preference to goto whenever possible. Since the break statement only exits from one level of the loop, a goto may be necessary for exiting a loop from within a deeply nested loop.
This example demonstrates the goto statement:
void main()
{
int i, j;
for ( i = 0; i < 10; i++ )
{
printf( "Outer loop executing. i = %d\n", i );
for ( j = 0; j < 3; j++ )
{
printf( " Inner loop executing. j = %d\n", j );
if ( i == 5 )
goto stop;
}
}
/* This message does not print: */
printf( "Loop exited. i = %d\n", i );
stop: printf( "Jumped to stop. i = %d\n", i );
}

In this example, a goto statement transfers control to the point labeled stop when i equals 5.

Homepage von PS-Trainer - C-Entwicklung - Flusskontrolle - an PS-Trainer

Aktuelle Daten dieser Seite Letzte Änderung:
  Geocities

 

 

 

Hosted by www.Geocities.ws

1