Chapter 11 statement

xiaoxiao2021-03-06  15

Chapter 11 statement

The C statement is a program element for controlling how the object is operated in order. This chapter includes:

* Overview

* Number statement

* Expression statement, these statements are the side effects of an expression or their return value.

* Empty statement, these statements can be provided in C grammar requires statements, but do not perform any action.

* Composite statement, these statements are the statement groups included in the curly bracket ({}). They can be used in any places where you need a single statement.

* Select a statement that performs a test, if the test is true (non-0), execute a part of the code; if the test is fake, another partial code can be executed.

* Iterative statement, these statements have repeatedly executed a piece of code until a designated termination condition is satisfied.

* Jump statement, these statements, or another place to immediately forward the function or return to the function from the function.

* Instructions statement, indicating that the name is introduced into a program (Chapter 6 "Description" provides more detailed information on the description).

* Abnormal processing statement, including C exception handling (try, throw or catch) and structural exception processing (__TRY / _ _EXCEPT, _ _TRY / _ _FINALLY). The TRY_EXCEPT statement provides a method to get the control of a program when the event is properly terminated; try_finally and levave statements provide a method, and the execution of the code is interrupted to ensure the execution of the code.

Site outline

The C statement is sequentially executed unless the expression statement, the selection statement, iterative statement, or the jump statement specifically modifies that order.

Syntax statement:

Label statement

Expression statement

Composite statement

Select statement

Iterative statement

Jump statement

Description statement

Try-throw-catch

In most cases, the syntax of the C statement is identical to ANSI C. The basic difference between the two is: in C, explaining that only the beginning of the block is allowed; C adds declaration-statement, effectively Remove this limit. This allows you to introduce variables in a program for pre-counting initialization values. Describe the variable in the block also allows you to apply accurate control of the range and survival of these variables.

Label statement

The label statement is directly to a given statement directly to a given statement. This statement must be labeled, see "Using the label with goto statement" and "using label in the case statement".

grammar

Number statement:

Identifier: statement

CAST constant expression: statement

DEFAULT: statement

Use the label with goto statement

An identifier indicator in the source program illustrates a label, only one goto statement can transfer control to a identifier sign number. The following code segment gives the case where the GOTO statement and one identifier sign are jumped from a close nested loop:

For (p = 0; p

FileOpenerror:

CERR << "Fatal File Open Error, Processing Interrupted./N"); In the above example, if an unknown file is displayed, the GOTO statement directly turns to the statement of the print error message.

A label cannot appear independently, but must always be attached to a statement. If a label is needed by itself, put a novel statement after the label.

The label has a function range and cannot be described in its function. But the same name can be used as a label in different functions.

Use the label in the case statement

The labels that appear after the CASE key cannot appear outside of the Switch statement (this limit is also available for Default keyword). The following code segment gives the correct use of the Case label:

// Microsoft window information processing cycle sample

Switch (msg)

{

Case WM_TIMER: // Processing Time Events

SetClassword (HWND, GCW_HICON, AHICON [NICON ]); showWindow (hwnd, sw_showna);

NICON% = 14;

Yield ();

Break; Case WM_Paint:

/ / Get a handle of the device context

// beginpaint issues WM_ERASEBKGND in the appropriate situation

MEMSET (& PS, 0x00, SIZEOF (PAINTSTRUCT));

HDC = BeginPaint (HWND, & PS);

/ / Notification window drawing has been completed

Endpaint (hwnd, & ps);

Break; Case

WM_CLOSE:

// Close this window and all sub-windows

Killtimer (hwnd, timer1);

DestroyWindow (hwnd);

IF (hwnd == hwndmain)

PostquitMessage (0); // Exit application

Break;

DEFAULT:

// No information specifically included by the CASE statement is adopted

Return DefWindowProc (Hwnd, Message, WPARAM, LPARAM);

Break;

}

Expression statement

Expression statements make the expression value. As a result of an expression statement, there is no control transfer or cycle.

Syntax expression statement:

Expression OPT;

All expressions in an expression statement are evaluated before performing the next statement. And all side effects are completed. The most common expression statement is assignment and function calls. C also provides an empty statement.

Empty statement

"Symposium" is an expression statement without an expression. It is useful in the language grammar requires a statement but does not have an expression, which consists of a semicolon.

The empty statement is typically used as a placeholder in a loop statement or a statement to place the label at the end of a composite statement or function.

The following code segment shows how the combined empty statement is copied to another:

Char * STRCPY (CHAR * DEST, Const Char * Source) {char * deststart = DEST; // will be assigned to DEST by the value referred to by Source until the end of the string While (* Dest = * Source ); / / Empty statement Return Deststart;}

Composite statement (block)

The compound statement consists of 0 or more statements included in the currency ({}), and a composite statement can be used in any place where the statement is required, and the composite statement is often referred to as "block".

grammar

Composite statement:

{Statement table OPT}

Statement table:

Statement

Statement table statement

The following example uses a composite statement as the statement section of the IF statement (see "IF statement" on the detailed syntax of the IF statement):

IF (Amount> 100) {cout << "Amount Was Too Large to Handle / N"; Alert ();} else balance- = amount;

Note: Because one instruction is a statement, one instructions can be one of the statements in the statement table. Therefore, in a composite statement, it is not explicitly explained as the name of Static, and has a local range and (for objects), detailed details of the processing with local scope have refer to Chapter 2 " "Range" in the basic concept.

Select statement

The selection statement IF and Switch of C provide a method to select some code.

grammar

Select statement:

IF (expression) statement

IF (expression) statement ELSE statement

Witch statement statement

IF statement

If the IF statement begins with the expression in parentheses, the expression must be an arithmetic or pointer type; or a class type of non-ambiguous conversion defined to an arithmetic or pointer type (see Chapter 3 " Conversion ").

In any form of two forms of IF syntax, if the expression value is a non-0 value (true), the statement dependent on the evaluation is executed; otherwise, it is skipped.

In the if ... Else syntax, if the expression results are 0, the second statement is executed.

The ELSE clause of the IF ... ELSE statement matches the IF statement that has not been matched in the previous previous, and the following code segment describes how this is working: if (condition1 == true) IF (condition2 == true) Cout << "condition1 true; condition2 true / n"; else cout << "condition1 true; condition2 false / n"; else cout << "condition1 false / n";

Many programmers explicitly indicate the matching of complex IF and ELSE clauses, as shown in the following example:

IF (condition1 == true) {if (condition1 == true) Cont << "Condition1 true; condition2 true / n"; else cont << "condition1 true; condition2 false / n";} else cont << "Condition1 False / N ";

Although the curb brackets are not strict, they indicate the relationship between the IF and ELSE statements.

SWITCH statement

The C Switch statement allows you to choose in multiple code sections, select the value that is dependent on the expression. The expression of "control expression" in parentheses must be turned into an integer or a class type and non-mutually transferred. Integer improvement is performed as described in Chapter 3, "Standard Conversion".

The Switch statement causes a non-conditional jump to, enter or skip the statement to "switch body", depending on whether the value of the control expression, the value of the CASE label, and the existence of the default label. Switchers are typically a composite statement (although this is not a grammar requirement). Normally, some of the statements in the switch body use a CASE label or marked with a default label. The tag statement is not a syntax, but it is meaningless. The Default label can only appear once.

grammar

Case constant expression: statement

DEFAULT: statement

The constant expression in the CASE label is converted to the type of control expression, and then the equality is compared. In a given Switch statement, the constant expression in the CASE statement does not have the same value of the same value. Its behavior is shown in Table 5.1:

Table 5.1 Switch statement behavior

Conditional operation The value converted to the lifted control expression control to the statement after the label does not have a constant in the CASE label. There is a default label control to the default label without a constant in the CASE label. Match, there is no default label control to the Switch statement behind the SWITCH statement

An internal block of the Switch statement can contain a definition with initialization, as long as they are reachable, that is, not by all possible paths. The name introduced with these instructions has a local range. The following code segment shows how the Switch statement works:

Switch (* argv [1])) {// error, not reachable description char Szchentered [] = "character entered was:"; Case'A ': {// szchentered instructions are feasible, for local scope Char szchentered [] = "Character Entered Was:"; cout << szchentered << "a / n";} Break; Case'B ': // Szchentered value Unexpected COUT << Szchentered << "B / N" The value of Break; Default: // szchentered undefined cout << szchentered << "Neither a nor b / n"; Break;} Switch statement can be nested. In this case, the CASE or DEFAULT label corresponds to the Switch statement containing the deepest nest of their deepest.

E.g:

Switch (msg) {copy wm_command: // window command, find more switch (wparam) {case IDM_F_NEW: // File Create a 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: // Requires Heavy Pictures Break; Default: Return DefWindowProc (Hwnd, Message, WPARAM, lparam;

The above code segment comes from the Microsoft Windows message loop, which shows how the Switch statement is nested. The Switch statement selected by the value of WPARAM is performed only when the MSG is WM_COMMAND. The case IDM_F_NEW and IDM_F_OPEN are selected as the Switch statement of the micro.

The control is not blocked by the Case or Default label. To end execution at the end of the composite statement, insert a BREAK statement. This will control the statement behind the Switch statement. This example describes how to "pass down" unless a BREAK statement:

Bool fclosing = false;

...

Switch (wparam) {copy idm_f_close: // File Close Command Fclosing = true; // Save the command if (Document-> isDiRTY ()) if (Document-> Name ()) == " Untitled ") FileSaves (Document); Else Filesave (Document); if (fclosing) Document-> Close (); Break;}

The above code illustrates how to use the CASE label does not hinder the fact that the control process is used. If the Switch statement turns the control to IDM_F_SAVE, fclosing is false. Therefore, the document is not closed after the file is stored. However, if the Switch statement will transfer to IDM_F_CLOSE, the fclosing is set to a true value, and the code saved by the file is executed.

Iterative statement

The iterative statement allows statements (or compound statements) to perform 0 or more times in some cycle termination conditions. When these statements are composite statements, they are sequentially performed unless the BREAK statement or the Continue statement (the description of these statements see "BREAK statement" and "Continue Statements" later in this chapter). C offers three iterative words, while, do and for. Each iterates to its termination expression value is 0 (fake), or until the cycle termination is forced to use a BREAK statement. Table 5.2 summarizes these statements and their role; each of them is discussed in detail in subsequent chapters.

Table 5.2 C cycle statement

Scriptom evaluation position initialization increment while loop top no DO loop bottom no for loop top

grammar

loop statement:

While (expression) statement

DO statement while (expression)

FOR (for-initial statement expression OPT; expression OPT) statement

For-initial statement

Expression statement

Description statement

The statement section of an iterative statement cannot be a description, but it can be a composite statement that contains a description.

WHILE statement

The While statement repeats a statement until the specified termination condition (expression) evaluation is 0. The test of the termination condition is performed before the loop is executed each time; therefore, the While cycle executes 0 or more, depending on the value of the termination expression. The following code uses the While loop to cut a string tail space:

Char * Trim (char * szsource) {char * pszeos; // Set the character string tail pointer to the character of the character string tail Pszeos = szSource Strlen (szsource) - 1; while (pszeos> = szsource && * pszeos == '') * Pszeos - = '/ 0'; return szsource;}

The termination condition is evaluated at the top of the cycle, and if there is no tail space, the loop will never be executed. The expression must be an integer, a pointer type, or a type of type with a non-blurred conversion to a integer or pointer type.

DO statement

The DO statement repeats a statement until the specified termination condition (expression) evaluation is 0. The test of the termination condition is performed after each execution of the loop, so the DO loop executes or more, depending on the value of the termination of the expression. The following functions use the DO statement to wait for the user to press a specified key:

Void Waitkey (Char asciicode) {char chtemp; do {chtemp = _getch ();} while (chTEMP! = asCIicode);

Use a DO loop in the previous code instead of the While loop. Use the DO loop, _getch function is called before the termination condition is evaluated to obtain a keystroke value. This function can be written in the While loop, but it is not that simple:

Void waitkey (char asciicode) {char chtemp; chtemp = _getch (); while (chTemp! = asCIicode) {chtemp = _getch ();}}

The expression must be an integer, a pointer type, or a type of type with a non-blurred conversion to a integer or pointer type.

For statement

The FOR statement can be divided into three separate parts, as shown in Table 5.3.

Table 5.3 for circulating elements

When the content of the grammatical name is executed, the initial statement is often used to initialize the cyclic index before any other element of the for statement or the child statement, which can include expression or explanation 1 to the given repetition of the loop, including the first time Repeat an expression to evaluate a whole or execution. A class type expression 2 having an integer non-ambiguous conversion 2 is tested in the expression 2 after the expression 2 is evaluated at the end of the cycle, and the expression 1 is used to be used for incremental cyclic index.

The FOR initialization statement is often used to illustrate and initialize the cycle indicator variable, and the expression 1 is typically used to test cyclic termination standards. Expression 2 is often used in incremental cycle indicators.

The FOR statement repeats the statement until the expression 1 evaluation is 0, and the for-initialization statement, the expression 1 and the expression 2 domain are optional. The following For loop:

For-init-statement; expression1; expression2)

{

// statement

}

Equivalent to the following While loops:

For-init-statement; while (expression1) {// statement expression2;}

Use the for statement to specify an easy access to an infinite loop for:

For (;;)

{

// Statement to be performed

}

This is equivalent

While (1)

{

// Statement to be performed

}

The initial part of the for loop can be a description statement or an expression statement, including a novel statement. Initialization can include an expression and description of any order, separated by a comma. Any object in the For-initialization statement has a local range, just as it is just explained before the For statement. Although the name of the object can be used in a partial more than one for loop within the same range, it means that only once, for example:

#include void main () {for (int i = 0; i <100; i) cout << i i;;;; i 指 不 i 不 指 说明 指 说明 语语 语语 语语 语语 语, 语, 语, 语, Because it is still in this range for (i = 100; I> = 0; - i) cout << i << "/ n";}

Although the three domains of the FOR statement are typically used to initialize, terminate tests, and increments, they are not limited to these usage. For example, the following code prints from 1 to 100, and the child statement is empty statement:

#include void main () {for (int i = 0; i <100; cout << i << endl);

Jump statement

The C jump statement performs an immediate transfer of a control.

grammar

Jump statement:

Break;

CONTINUE;

Return Expression OPT;

GOTO identifier;

BREAK statement

The BREAK statement is used to exit a loop or Switch statement. It will control the statement that keeps followed by a loop subfitricance or Switch statement.

The BREAK statement only ends the most closely containing loop or Switch statement. In the loop, Break is used to terminate before the termination condition is equal to 0; in the switch statement, the BREAK statement is used to terminate the code segment prior to a CASE label.

The following example illustrates the usage of the BREAK statement in the for loop:

For (;;) // No stop condition {if (list-> atend ()) Break; list-> next ();}

COUT << "Control Transfers to Here./N";

Note: There are other simple methods to exit cycles. It is best to use the Break statement in a more complex loop because the loop may be difficult to say that there should be termination before several statements being executed.

See "Switch Statements" in this section on the example of using the Break statement in the SWITCH statement.

Continue statement

The Continue statement forces control immediately to the minimum cycle continuing statement that contains the loop. ("Loop Continue" is a statement containing loop control expressions). Therefore, the Continue statement can only be in a loop statement (although it may be a unique statement in the statement). In a FOR cycle, the execution of the Continue statement results in the evaluation of the expression 2, and then the expression 3.

The following example shows how to use the Continue statement to bypass the code segment to jump to the next iteration of the loop: #include /

/ Get a character from the string SzlegalString ended with 0. Returns the subscript of the input character

INT getlegalchar (char * szlegalstring) {char * pch; do {char ch = _Getch (); // Use the STRCHR library function to determine if the read character is in the string, if not, use the continue statement // cross the cycle The remaining nature IF (PCH = STRCHR (SZLEGALSTRING, CH) == null) Continue; // A character is entered in the character string SzlegalString, returns its subscript Return (PCH-SZLALSTRING); // Continue statement Control to this} while (1); return 0;} RETURN statement

Return statement allows a function to immediately turn the control back to the call function (or if it is the main function, control to the operating system). The RETURN statement accepts an expression that the value of the transfer function is transmitted. Void type functions, constructor, and destructuring functions cannot specify an expression in a return statement; all other types of functions must specify an expression in the return statement.

If you specify, the expression is converted to the type specified in the function description, as is an initialization. The conversion from an expression type to the function of the RETURN type causes the temporary object to create, "Temporary objects" in Chapter 11, and when more information is created. When the control flow exits the block containing a function defined, the result is the same as the result of the RETURN statement that does not have an expression. This is illegal for functions illustrated as a return value.

A function can have any number of Return statements.

GOTO statement

The goto statement will control unconditionally transfer to the named label, and the labels must be in the current function. For more information about the reference and goto statement, see "Number Statement" and "Number of Use with GOTO statements".

Description statement

Description introduces a new name to the current range, these names can be:

* Type name (Class, Struct, Union, Enum, TypeDef, and member pointers)

* Object Name

* Function Name

grammar

Description statement:

Description

If an explanation in one block is introduced to the name of the external description of the block, the description earlier during the dock is hidden, after the end, the previous description can be seen again.

Multiple instructions for the same name in the same block are illegal.

See "Description and Definition" and "Scope" in Chapter 2, "Basic Concept" on explanation and name hidden.

Automatic object description

In C , the object can be described as an auto or register keyword as an automatic storage class. If a partial object (object inside the function) does not use any storage class keyword, it is assumed to be Auto. C 's initialization and description of these objects is different from objects described with static storage classes.

Initialization of automatic object

The instruction statement of the object of the Auto or Register store is executed each time it is executed. The following example from the "Continue Statement" gives the initialization of the automatic object CH of the DO loop: #include

// Get a character from Squi SzlegalString ended in space. Returns the indicator of the input character

INT getlegalchar (char * szlegalstring) {char * pch; do {// Each time, this description statement is executed once CHAR CH = _Getch (); if (((pch = strchr (szlegalString, CH) == NULL Continue; // A character in the string szlegalString is entered, returns its indicator Return (PCH-SZLALSTRING);} while (1);}

Each repetition of the cycle (instructions each time), the macro _Getch is evaluated, and the CH is initialized by the results. When the RETURN statement will be controlled to the block externally, the CH is destroyed (in this case, the memory is revoked). Refer to "Storage Class" in Chapter 2, "Basic Concept" in the initialization.

Destructure of automatic object

Defines the object in the loop to exit from the block each time the loop is repeated, or when the control goes to the previous point, it is destroyed once. In the block instead of the object illustrated in the loop, it is destroyed when the block is exitted or when the control goes to the description.

Note: The destructor can simply meaning the allocation of the object or the destructor of the object to call the object. When the jump statement will be turned to a loop or block, the object destroyed from the block indicated from the block is not destroyed in the block that is transferred to it. When the control goes to the previous point, the object is destroyed.

Transfer of control

You can specify a program transfer over a program transfer with a GOTO statement or a Switch statement. Such a code is illegal unless an instruction includes an instructions including the initial, in blocks that appear on the jump statement.

The following example gives a circulation that describes and initializes the object Total, CH, and I, and an error GOTO statement will control the initializer.

// Read input until you enter a non-digital character

While (1) {int total = 0; char CH = _Getch (); if (ch> = '0' || CH <= '9') {goto label1; // error: Move the initializer INT of I i = ch-'0 '; label1: total = i;} // If the goto error does not appear, i will be destroyed here in the ELSE // Break statement, destroy Total and Ch Break;

In the previous example, the GOTO statement attempts to control the initializer that controls the I. However, if i is described but not initialized, the movement will be legal.

In the block of the block of the statement part of the statement of the statement, the TOTAL and CH objects are destroyed when using the BREAK statement exits the block.

Static object description

An object can be described as static storage with static or extern keywords. The local object must explicitly explain to static or externs to have a static storage class. All global objects (objects outside all functions) have a static storage class where you cannot explain static instances in a micromolder program.

Initialization of static objects

Global objects are initialized at the beginning of the program (more information on the constructors and sectations of global objects, see "Additional start-up considerations" in Chapter 2, "Atmosphere", and "Additional End Considering").

Note It is initialized when the local object of Static is initialized in the program process. The following classes described in Chapter 2, "Basic Concept" show how this is working:

#include

#include

/ / Define a class record initialization and destructive

Class initdemo {public: initdemo (char * szwhat); ~ initdemo (); private: char * szobjname;}:

// * InitDemo class constructor

INitDemo :: initdemo (char * szwhat) {if (szWhat! = 0 && strlen (szWhat)> 0) {szobjName = new char [strlen (szwhat) 1]; strcpy (szobjname, szwhat);} else szobjname = 0 Clog << "Initializing:" << Szobjname << "/ n";

// initdemo destructor

INitDemo :: ~ INitDemo () {if (SzobjName! = 0) {clog << "Destroying:" << SzobjName << "/ n"; delete szobjname;}}

// master function

Void Main (int Argc, char * argv []); {IF (argc <2) {CERR << "Supply a one-letter argument./n"); return -1;} if (* argv [1] = = 'A') {cout << "* argv [1] WAS AN 'A' / N"; // Describes Static Local Object Static InitDemo I1 ("STATIC I1");} else cout << "* Argv [1 ] WAS NOT AN 'A' / N ";} If the command line parameter provided to this program is started with lowercase letters" A ", the description of I1 is executed, initialization, the result:

* Argv [1] WAS AN 'A'

Initializing: Static I1

Destroying: Static I1

Otherwise, the description of the flow around I1 is:

* Arg [1] WAS Not an 'A'

When a static partial object is described with an initializer not equal to a constant expression, the object is given a given value 0 (converted to the appropriate type) before the first entry block is performed. But the object is invisible, and the constructor is called until the actual point of the description is called.

At the description, the constructor of the object (if the object is a class type) is called as scheduled (the static partial object is only initialized when they are first seen).

Destructure of static object

The local static object is destroyed during the termination specified by the atexit.

If a static object is not constructed because the program control flows around the instructions, do not try to destroy the object.

Abnormal processing

Microsoft C supports two exception handling, C exception handling (Try, throw, catch), and structural exception processing (__TRY / _ _EXCEPT, _ _TRY / _ _FINALLY). If possible, it should be processed with an abnormality process of C without using the structure exception.

Note: In this section, the term "structural abnormality processing" and "structural" (or "C)) only refers to the structural abnormality processing mechanism provided by Win32, reference (or" C exception " Both refers to the C exception handling mechanism.

Although structural exception handling works with C and C source files, it is not designed for C , for C programs, you should use C exception handling.

TRY, CATCH and THROW statements

The C language provides internal support for processing exceptions, and the abnormal situation is the "exception" known, which may appear during your program execution.

Try, throw and catch statements have been added to the C language to achieve exception processing. With C exception handling, your program can deliver unexpected events to higher execution context, which can be restored from these exception events. These exceptions are processed by the code outside the normal control flow. The Microsoft C compiler is to implement the C exception handling mode based on ISO WG21 / ANSI X3J16 working files in the standard of C evolution.

grammar

TRY block:

TRY Composite Schemration Processor Table

Processor table:

Processor processor table OPT

processor:

Catch (abnormal description) Composite statement

Abnormal description:

Type Indicator

Type indicator, abstract specifier

Type indicator

... throw-expression:

Throw Assignment Expression OPT

The composite statement after the TRY clause is the protection segment of the code. Throw Expression "Discard" A exception, the composite statement after the CatCH clause is an exception processor, and the "capture" is discarded by the Throw expression. Exception Description statement indicates the type of abnormality processing of subsepts, and the type can be any valid data type, including C classes. If the exception statement is a omitted number (...), the CatCH clause handles any type of exception, including C. Such a processor must be the last processor of its TRY block. THROW operates similar to the RETURN statement. Note: Microsoft C does not support functional Throw feature mechanisms, such as 15.5 of the ANSI C draft. In addition, it does not support the Function-Try-block described in the 15 sections of the ANSI C draft. The execution process is as follows:

1. Controls to reach the TRY sentence in normal order, and the protection segment (within the TRY block) is executed.

2. If there is no abnormality during the execution of the protection segment, the Catch clause following the TRY block is not executed. The statement followed by the last CatCH clause followed by an abnormally discarded TRY followed.

3. If there is an abnormality that is abnormal during the execution of the protection segment or in any routine (directly or indirect call), you create an exception object from the object created by the throw operand (this hidden pointing " May contain a copy constructor). At this point, the compiler is looking for a Catch clause (or a CATCH processor that can handle any type of exception) in a higher execution context capable of processing discard type. The Catch handler is checked in the order in which it appears after the TRY block. If the appropriate processor is not found, the next dynamically enclosed TRY block is checked. This process continues until the outermost closed TRY block is checked.

4. If the matching processor is not found, or if an abnormality is not automatically branched, the predefined run function Terminate is called before the processor gets the control. If an exception occurs after the abnormality is discarded, Terminate is called before the loop expansion starts.

5. If a matching catch processor is found, it is captured by a value, its shape is initialized by copying anomaly object. If it is captured by reference, the parameter is initialized to point to an abnormal object, and after the meticulum is initialized, the "loop exhibition opening stack" process begins. This includes destructors of all automatic objects created between the TRY blocks corresponding to the CATCH processor and the abnormal discard location. The sequence is carried out in the order in contrast to the construction. The CATCH processor is executed and the program is restored to the execution following the last processor (ie, the first statement or constructor of the CATCH processor). Control can only enter a CATCH processor through a discarded exception, but never pass the CASE label in the GOTO statement or the Switch statement.

The following is a simple example of a TRY block and its corresponding CATCH processor. This example detects the failure of the memory allocation operation using the New operator. If New is successful, the CATCH processor will never perform:

#include int main () {char * buf; try {buf = new char [512]; if (buf == 0) throw "Memory Allocation Failure!";} catch (char * STR) {COUT << "Exception Raised:" << str << '/ n';} // ... return 0;}

The operand of the throw expression indicates an exception of a char * type being discarded. It is processed by a CATCH processor indicating an exception capable of capturing a char *. In the memory allocation failure event, this is the output obtained from the previous example:

Exception Raised: Memory Allocation Failure!

The true ability of C abnormality processing is not only the ability to handle various types of abnormalities, but also the ability to automatically call all local objects before the stack cycle deployment for all partial objects constructed before the abnormal discard.

The following example demonstrates a C exception handler using a class with a semantic semantic:

#include void myfunc (void); class ctest {public: ctest () {}; const char * showreason () const {return "Exception in ctest class."}} Class cdtordemo {public: cdtordemo (); ~ cdtordemo ();}; cdtordemo :: cdtordemo () {cout << "constructing cdtordemo./n";} cdtordemo :: ~ cdtordemo () {cout << "destructurement cdtordemo ./n"; }void myfunc () {CDTORDEMO D; cout << "in myfunc (). throwing ctest exception./N"; throw ctest ();} int main () {cout << "in main./ N "; try {cout <<" in try block, call myfunc () ./ n "; myfunc ();} catch (ctest e) {cout <<" in catch handler./n "; cout <<" caught CTEST Exception Type: "; cout << E.SHOWREASON () <<" / n ";} catch (char * str) {cout <<" CANGHT SOME OTHER EXCEPTION: "<< str <<" / n ";} Cout << "Back in main. Execution resumes here./N"; return 0;}

The following is the output of the above example:

In Main.in Try Block, Calling Myfunc ()

. Constructing cdtordemo.

IN myfunc (). Throwing ctest exception.

DESTRUCTING CDTORDEMO.

IN catch handler.

CAUGHT CTEST EXCEPTION TYPE; Exception In Ctest Class.

BACK IN Main. Execution Resumes Here.

Note that in this example, the abnormal parasis (the parasis of the CatCH clause) is described in two CATCH processors:

Catch (ctest e)

// ...

Catch (char * STR)

// ...

You don't need to illustrate this parameter; in many cases, it is possible to notify the processor to have a particular type of exception. But if you don't explain an exception object in an exception description, you will not be able to access the object in the Catch handler clause.

A THROW expression that does not operate has discarded the abnormality that is currently being processed. This expression should only appear in a Catch processor or from the function called inside the CATCH processor, the abnormality object discarded again is Source exceeding object (not copy). E.g:

Try {throw csomeoThereXception ();

Catch (...) // Processes all exception {// Responsible for exceptions (perhaps only partial) // ... throw; // will pass abnormally to some other processor}

Unprocessed exception

If the matching processor (or omitted CATCH processor) is not found for the current exception, the predefined Terminate function is called (you can also explicitly call Terminate in any of your processors). The default action of TERMINATE is to call Abort. If you want Terminate to call some other function in your program before exiting the app, use the function name to be called as a single parameter to call the set_terminate function. You can call Set_Terminate anywhere in your program. The TERMINATE routine always calls a given last function as a parameter of set_terminate. For example: #include // Used to function prototype

// ...

Void Term_Func () {//...} whit main () {TRY {// ... set_terminate (tHM_FUNC); // ... throw "out of memory!"; // No Catch processor for this exception } catCH (int) {cout << "integer exception raised.";} return 0;

The Term_Func function should terminate the program or the current thread, ideally by calling EXIT. If it is not, it is returned to its caller, then Abort is called.

For more information on C abnormal processing, see "C Reference Manual" in Margaret A.ellis and Bjarne Stroustrup.

Structure abnormal processing

___ try / __ eXcept and __try / __ finally statement is the expansion of Microsoft to C language so that the application is controlled after the event is performed normally executed.

Note: The structural exception handling works with the C and C source files. But it is not specially designed for C . Although the despite the destructive function of local objects will be called if you use structural exception processing in a C program (if you use / gx compiler option); however, you can use C exception to ensure that your code has better portability . The C abnormal handling mechanism is more flexible, which can handle any type of exception.

For more information, see "Try-Finally Statements" in Chapter 5, "Statements" in the "C Language Reference" in front of this volume.

grammar

TRY-EXCEPT statement:

__TRY composite statement

__except (expression) Composite statement

TRY-FINALLY statement:

__TRY composite statement

__finally complex statement

If you have a C mode that uses structured exception handling, they can be mixed with C mode using C abnormality.

When a C (structured) abnormality is generated, it can be processed by a C processor, or captured by CATCH processor of C , which is more dynamically close to the abnormal context. One of the two modes is that when C is abnormal, it is always no symbol integer, and a C exception can be any type. That is, C exception is identified by an unsigned value, while C discards is identified by the data type. However, when a CATCH processor of a C can capture a C abnormality (eg, pass a "" CATCH processor), a CatCH processor) can also be processed as a type of abnormality by using a C abnormality bypassing. By derived from this class, each C abnormality can belong to a specific derived class.

To use the C exception Wrapper class, you can install a custom C converter function that is called by the internal exception handling mechanism while generating C exceptions each time. In your converter function, you can discard any type of exception, which can be captured by a corresponding match C CATCH processor. To specify a custom translation function, use your translation function name as a single parameter to call the _SET_SE_TRANSLATOR function.

转载请注明原文地址:https://www.9cbs.com/read-46752.html

New Post(0)