● 左操作数为可修改左值;右操作数为右值,可以转换为左操作数的类型

    ● 赋值操作符是右结合的,求值结果为左操作数

    1. #include <iostream>
    2. int main()
    3. {
    4. int x;
    5. int y;
    6. x = y = 5;
    7. std::cout << x << " " << y << std::endl;
    8. }

    Output:

    1. 5 5
    1. #include <iostream>
    2. int main()
    3. {
    4. int x1;
    5. (x1 = 2) = 5;
    6. ((x2 = 2) = 5) = 1;
    7. std::cout << x1 << " " << x2 << std::endl;
    8. }

    Output:

    1. 5 1

    ● 可以引入大括号(初始化列表)以防止收缩转换( narrowing conversion

    1. #include <iostream>
    2. int main()
    3. {
    4. short x = 0x80000003;
    5. std::cout << x << std::endl;
    6. }

    Output:

    1. 3
    1. #include <iostream>
    2. int main()
    3. {
    4. short x ={ 0x80000000 };
    5. std::cout << x << std::endl;
    6. }

    程序无法运行,并给出报错:

    1. <source>:5:14: error: constant expression evaluates to 2147483648 which cannot be narrowed to type 'short' [-Wc++11-narrowing]
    2. short x ={ 0x80000000 };
    3. ^~~~~~~~~~

    一个特殊例子:

    1. #include <iostream>
    2. int main()
    3. {
    4. int y = 3;
    5. short x;
    6. x = { y };
    7. std::cout << x << std::endl;
    8. }

    报错:

    1. error: non-constant-expression cannot be narrowed from type 'int' to 'short' in initializer list [-Wc++11-narrowing]

    因为这里的{ y }可能会有narrowing conversion的风险
    修改:int y = 3; to constexpr int y = 3; 这里不使用const,因为对应的是运行期常量,仍有可能发生narrowing conversion

    ● 小心区分 = 与 ==

    ● 复合赋值运算符