// Assuming these initializations
int x;
float y;
Run Code Online (Sandbox Code Playgroud)
这有什么区别:
x = y = 7.5;
Run Code Online (Sandbox Code Playgroud)
和这个:
y = x = 7.5;
Run Code Online (Sandbox Code Playgroud)
为什么第一个将y值打印为7.5,第二个将值打印y为7.00?
解释很简单:=从右到左是关联的,这意味着x = y = 7.5;被评估为x = (y = 7.5);与以下相同:
y = 7.5; // value is converted from double to float, y receives 7.5F
x = y; // value of y is converted from float to int, x receives 7 (truncated toward 0)
Run Code Online (Sandbox Code Playgroud)
而y = x = 7.5;评估为y = (x = 7.5);:
x = 7.5; // 7.5 is converted to int, x receives value 7 (truncated toward 0)
y = x; // value of x is converted to float, y receives 7.0F
Run Code Online (Sandbox Code Playgroud)
这些隐式转换可能很不直观。您可能希望提高警告级别,以使编译器警告您潜在的错误和有害的副作用。