Chapter 6:Statements

Section 6.1 Simple Statements

Null Statements

  • The simplest form of statements is the empty, or null statement. It takes the following form (a single semicolon):

           ;  // null statement

  • A null statement is usefull where the language requires a statement but the program's logic does not. Such usage is most common when a loop's work can be done within the condition.
  • A null statement should be commented, so that anyone reading the code can see that the statement was omitted intentionally.
  • Extraneous null statements are not always harmless, such as an exrta semicolon following the condition in a while or if can drastically alter the prgrammer's intent.

Section 6.2 Declarations Statements

  • Defining or declaring an object or a class is a statement.

Section 6.3 Compound Statements (Blocks)

  • A compound statement, usually referred to as a block, is a (possibly empty) sequence of statements surrounded by a pair of curly braces, a block is a scope.
  • Unlike most other statements, a block is not terminated by a semicolon.
  • We can also define an empty block.

 

Section 6.4 Statement Scope

  • Variables defined in a condition must be initialized. The values tested by the condition is the value of the intialized object.
  • Variables defined as part of the control structure of a statemnet are visible only until the end of the statement in which they are defined.
  • If the program needs to access the value of a variable used in the control statement, then that variable must be defined outside the control structure.

Section 6.5 The if Statement

  • The syntactic form of the plain if is the following:

             if (condition)

               statement

  • The condition must be enclosed in parentheses, it can be an expression, or an initialized declaration.

Statement Block as Target of an if

  • It is a somewhat common error to forget the  curly braces when multiple statements must be executed as a single statement.

6.5.1 The if Statement else Branch

  • The synatactic form of the if else statement is:

             if (condition)

               statement1

             else

               statement2

Dangling else

  • The problem, usually referred to as the dangling-else problem, occurs when a statement contains more if clauses than else clauses, the question then arises: To which if does each else clause belong?
  •  In C++, however, the dangling-else ambiguity is resolved by matching the else with the last occuring unmatched if.

 

Section 6.6 The switch Statement

  • A switch statement provides a more convinient way to write deeply nested if/else logic.

6.6.1 Using a switch

6.6.2 Control Flowing within a switch

  • It is a common misunderstanding to expect that only the statements associated with the matched case label are executed. However, execution continues across case boundaries until the end of the switch statement or a break is encountered.
  • Forgetting to provide a break is a common source of bugs in switch statements.
  • Although it is not strictly necessary to specify a break statement after the last label of a switch, the safest course is to provide a break after every label, even the last. If an additional case label is added later, then the break is already in place.

break statements Aren't Always Appropriate

  • There is one common situation where the programmer might wish to omit a break statement from case label, allowing the program to fall through multiple case labels.
  • Deliberately omitting a break at the end of a case happens rarely enough that a comment explaining the logic should be provided.

6.6.3 The default Label

  • The default label provides the equivalent of an else clause.
  • It can be useful always to define a default label even if there is no processing to be done in the default case. Define the label indicates to subsequent readers tahtthe case wass considered but that there is no work to be done.

6.6.4 switch Expression and Case Labels

  • Case labels must be constant integral expressions, it is also an error for any two case labels to have the same value.

6.6.5 Variable Defintions inside a switch

  • Variables can be defined following only the last case or default label.

 

Section 6.7 The while Statement

  • A while statement repeatedly executes a target statement as long as a condtion is true. Its syntacitic form is:

                       while (condition)

                         statement

  • The condition can be an expression or an initialized variable definition.
  • Variables defined in the condition are created and destroyed on each trip through the loop.

Using a while Loop

  • The assignment in the while loop represents a very common usage. Because such code is widespread, it is important to study this expression until its meaning is immediately clear.

  

Section 6.8 The for loop Statement

  • The syntactic form of a for statement is:

             for (init-statement coindition; expression)

               statement

  • In general, the init statement is used to initialize or assign a starting value that is modified over the course of the loop, condition serves as the loop control.
  • The expression usually is used to modify the variable(s) initialized in init-statement and tested in condition, it is evaluated after each iteration of the loop.
  • As usual, statement can be either a single or a compound statement. 

Using a for Loop

  • It is worth remembering that the visibility of any object defined within the for header is limited to the body of the for loop.

6.8.1 Omitting Parts of the for Header

  • A for header can omit any (or all) of init-statement, condition, or expression.
  • The init-statment is omitted if an initialization is unnecessary or occurs else-where.
  • If the condition is omitted, then it is equivalent to having written true as the condition.
  • If the expression is ommitted, then the loop must exit through a break or return or the loop body must arrange to change the value tested in the condition.

6.8.2 Mutiple Definitions in the for Header

  • Multiple objects may be defined in the init-statement; however, only one statement may appear, so all the objects must be of the same general type.

  

Section 6.9 The do while Statement

  

Section 6.10 The break Statement

  • A break statement terminates the nearest enclosing while, do-while, for, or switch staement.
  • A break can appear only within a loop or switch statements or in a statement nested inside a loop or switch.

  

Section 6.11 The continue Statement

  • A continue statement causes the current iteration of the nearest enclosing loop to terminate.
  • In a while or do while loop execution resumes with the evaluation of the condition. In a for loop, execution continues by evaluating the expression in the for header.
  • A continue statement can appear only inside a for, while, or do while loop, including inside blocks nested inside such loops.

  

Section 6.12 The goto Statement

  • A goto statement provides an unconditional jump from the goto to a labeled statement in the same function.
  • Uses of gotos has been discouraged since the late 1960s. Any program that uses a goto can be rewritten so that it doesn't need to goto.
  • The syntactic form of a goto statement is

                        goto label:

  • A labeled statement is any statement that is preceded by an identifier followed by a colon
  • A goto may not jump forward over a variable definition, if definitions are needed between a goto and its corresponding label, the definitions must be enclosed in block.
  • A jump backward over an already executed defintion is okay. Jumping back to a point before a variable is defined destroys the variable and constucts it again.

 

Section 6.13 try Blocks and Exception Handling

  • Exceptions are run-time anomalies, such as running out of memory or encountering unexpected input.
  • Exceptions support this kind of communication between the error-detecting and error-handling parts of a program.
  • throw expressions, which the error-detecting parts uses to indicate that it encountered an error that it connot handle. We say that a throw raises an exceptional condition.
  • try blocks, which the error-handling part uses to deal with an exception. A try block starts with keyword try and ends with one or more catch clauses. Exception thrown from code executed inside a try block are usually handled by one of the catch clauses. Because they "handle" the exception, catch clauses are known as handlers.
  • A set of exception classes defined by the library, which are used to pass the information about an error between athrow and an associated catch.

6.13.1 A throw Expression

  • An exception is thrown using throw expression, which consists of the keyword throw followed by an expression.
  • A throw expression is usually followed by a semicolon, making it into an expression statement. The type of the expression determines what kind of exception is thrown. 

6.13.2 The try Block

  • The general form of a try block is

              try {

                program-statements

              } catch (exception-specifier) {

                                            handler-statements

 

              } catch (exception-specifier) {

 

                                            handler-statements

              } //...

  • A try block begins with the keyword followed by a block, which an usual is a sequence of statements enclosed in braces. Following this block is a list of one or more catch clauses which  consists of three parts: keyword catch, exception, the associated block is executed.
  • The program-statements inside the try constitute the normal logic of the program, they can contain any C++ statements, including declarations.
  • Variables declared in this block are inaccessible outside the block - in particular, they are not accessible to the catch clauses.           

Writing a Handler

Functions Are Exited during the Search for a Handler

  • In complex systems the execution of path of a program may pass through mutiple try blocks before encountering code that actually throws an exception.
  • If no catch clause capable of handling the exception exists, program execution is transferred to a library function named terminate, which is defined in the exception header. The behavior of that function is system dependent, but it usually aborts the program.

  

6.13.3 Standard Exceptions

  • The C++ library defines a set of classes that it uses to report problems encountered in the functions in the standard library which are defined in four headers.
  • The exception header defines the most general kind of exception class named exception. It communicates only that an exception occurs but provides no additional information.
  • The stdexcept header defines several general purpose exception classes.
  • The new header defines the bad_alloc exception type, which is the exception thrown by new if it cannot allocate memory.
  • The type_info header defines the bad_cast exception type.

Standard Library Exception Classes

  • The library exception classes have only a few operations. The exception, bad_alloc, and  bad_cast types define only a default constructor; it is not possible to provide an intializer for objects of these types. The other exception types define only a single constructor that takes an string intializer.
  • The exception types define only a single operation named what. That function takes no arguments and returns a const char*.

Section 6.14 Using the Preprocessor for Debugging

  • We can write conditional debugging code using the NDEBUG preprocessor variable. If NDEBUG is not defined, then the program writes the message to cerr, otherwise then the program executes without ever passing through the code between the #ifndef and the #endif
  • By default, NDEBUG is not defined, meaning that by default, the code inside the #ifndef and #endif is processed.
  • The preprocessor defines four other constants that can be useful in debugging:

            __FILE__ name of the file.

            __LINE__ current line number.

            __TIME__ time the file was compiled.

            __DATE__ date the file was compiled.

  • Another common debugging techinque uses the NDEBUG preprocessor variable and the assert preprocessor macro. The assert macro is defined in the cassert header.
  • The assert macro takes a single expression, which it uses as a condition:

                    assert(expr)

原文链接: https://www.cnblogs.com/alldots/archive/2012/05/03/2480611.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Chapter 6:Statements

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/49339

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午1:00
下一篇 2023年2月9日 上午1:02

相关推荐