● 左操作数为可修改左值;右操作数为右值,可以转换为左操作数的类型
● 赋值操作符是右结合的,求值结果为左操作数
#include <iostream>
int main()
{
int x;
int y;
x = y = 5;
std::cout << x << " " << y << std::endl;
}
Output:
5 5
#include <iostream>
int main()
{
int x1;
(x1 = 2) = 5;
((x2 = 2) = 5) = 1;
std::cout << x1 << " " << x2 << std::endl;
}
Output:
5 1
● 可以引入大括号(初始化列表)以防止收缩转换( narrowing conversion )
#include <iostream>
int main()
{
short x = 0x80000003;
std::cout << x << std::endl;
}
Output:
3
#include <iostream>
int main()
{
short x ={ 0x80000000 };
std::cout << x << std::endl;
}
程序无法运行,并给出报错:
<source>:5:14: error: constant expression evaluates to 2147483648 which cannot be narrowed to type 'short' [-Wc++11-narrowing]
short x ={ 0x80000000 };
^~~~~~~~~~
一个特殊例子:
#include <iostream>
int main()
{
int y = 3;
short x;
x = { y };
std::cout << x << std::endl;
}
报错:
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
● 小心区分 = 与 ==
● 复合赋值运算符