C++ Primer reading notes - the use of statements

① empty statement

        The simplest statement is the empty statement, which consists of only a single semicolon;

② switch statement

        The case keyword and its corresponding value are called a case label, and the case label must be an integer constant expression;

char ch = getVal();
int iVal = 42;
switch(ch){
    case 3.14: // 错误,case标签不是一个整数
    case ival: // 错误,case标签不是一个常量
    ……
}

③ range for statement

        The new C++11 standard introduces a range for statement, which can traverse all elements of a container or other sequence;

       The expression must be a sequence, which can be an initialization list enclosed in curly braces, an array, or objects of types such as vector and string. These objects are characterized by having begin and end members that can return iterators;

        declaration defines a variable, and each element in the sequence must be able to be converted into the type of the variable. Generally, the auto type specifier is used to declare the variable; if the element in the sequence needs to be written, the loop variable must be declared as a reference type;

for (declaration : expression)
    statement

std::vector<int> v = {0, 1, 2, 3};
for (auto &r : v)
    r *= 2; // 将 v 中所有元素翻倍
// 范围 for 语句与以下传统 for 语句等价
for(auto beg = v.begin(), end = v.end(); beg != end; ++beg){
    auto &r = *beg;
    r *=2;
}
// 因此不能通过范围 for 语句增加 vector 对象的元素,因为范围 for 语句预存了 end() 的值;

④ break statement and continue statement

        The break statement is responsible for terminating the while, do while, for, and switch statements closest to it, and continues execution from the first statement after these statements;

        The continue statement terminates the current iteration in the nearest loop and immediately starts the next iteration, which can only appear inside a for, while, do while, or statement or block nested in such a loop;

        The scope of the break statement is limited to the nearest loop or switch; the continue statement that appears in the nested loop only acts on the nearest loop; unlike the break statement, only when the switch statement is nested inside the iteration statement , to use the continue statement in the switch;

⑤ goto statement

The function of the goto statement is to unconditionally jump         from the goto statement to another statement in the same function ; it is generally not recommended to use the goto statement in the program because it can make the program difficult to understand and modify;

goto label;

// label 是用于标识一条语句的标示符,其定义的带标签语句如下:
label : xxxxx;    // xxxx为具体的语句

        The goto statement cannot skip the statement with the initialization variable definition, that is, the following code will make an error, because the goto statement skips the statement with the initialization definition of int a = 30;

// 错误代码如下:
#include "iostream"

int main(int argc, char* argv[]){
    goto label;
    int a = 30;
    std::cout << "a: " << a << std::endl;
    label :
        int b = 50;
        std::cout << "b: " << b << std::endl;

    return 0;
}

// 正确代码如下:
#include "iostream"

int main(int argc, char* argv[]){
    int a = 30;
    goto label;
    std::cout << "a: " << a << std::endl;
    label :
        int b = 50;
        std::cout << "b: " << b << std::endl;

    return 0;
}

⑥ Exception handling mechanism

        The exception handling mechanism provides support for the cooperation of exception detection and exception handling in the program; in C++ language, exception handling includes: throw expression, try statement block and exception class;

        Throw expression: The exception detection part uses throw expression to express the unhandled problems it encounters, generally called throw raises an exception;

        Try statement block: The exception handling part uses a try statement block to handle exceptions, which starts with the keyword try and ends with one or more catch clauses; the exception thrown in the try statement block is usually handled by a catch clause, Therefore the catch clause is called exception handling code;

        Exception class: used to pass exception specific information between throw expressions and related catch clauses;

        A throw expression consists of the keyword throw followed by an expression, where the type of the expression is the type of the exception being thrown;

        Throwing an exception will terminate the current function and transfer control to code that can handle the exception;

// 当数据的 ISBN 不相同时,抛出一个 runtime_error 类型的异常对象
if(item1.isbn() != item2.isbn()){
    throw runtime_error("DATA must refer to same ISBN");
}

        The general grammatical form of a try statement block is as follows, that is, it consists of a try block and one or more catch clause blocks; the catch clause includes three parts: the keyword catch, the declaration of an object in parentheses (called an exception statement), and a piece;

        When a catch clause is selected to handle an exception, the corresponding block will be executed; once the catch is completed, the program jumps to the statement after the last catch clause of the try statement block to continue execution;

try{
    program-statements
} catch (exception-declaration){
    handler-statements
} catch (exception-declaration){
    handler-statements
}
// 代码实例
#include <iostream>
#include <stdexcept>

int main(int argc, char* argv[]){
    int color;
    std::cin >> color;
    std::cout << "your input is : " << color << std::endl;
    try{
        if (color > 255){
            // 抛出上溢错误
            throw std::overflow_error("上溢"); 
        } 
        else if(color < 0){
            // 抛出下溢错误
            throw std::underflow_error("下溢");
        }
    }
    // 捕获std::overflow_error的错误
    catch(std::overflow_error err1){ 
        color = 255;
    }
    // 捕获std::underflow_error的错误
    catch(std::underflow_error err2){ 
        color = 0;
    }
    std::cout << "Real valid data: " << color << std::endl;

    return 0;
}

         In the above code, different exceptions are thrown according to different detection conditions, and are processed by the corresponding catch statement; the type of exception thrown can use the provided standard exception, or you can customize the exception type. The above code uses the header file Two standard exception classes provided by stdexcept: std::overflow_error and std::underflow_error;

        When an exception is thrown, a function that can handle the exception will be searched; when no matching catch clause is found, the program will call the terminate function to terminate the program;

Guess you like

Origin blog.csdn.net/weixin_43863869/article/details/130394140