[英]Java inline int swap. Why does this only work in Java
I was asked to write a swap without using temp variables or using xor and i came up with this. 我被要求在不使用临时变量或使用xor的情况下编写交换,我想出了这个。
In Java, this works, but in C/C++ this does not work. 在Java中,这可行,但在C / C ++中,这不起作用。
I was under the impression that this would always work since the value of 'a' on the left side of the '|' 我的印象是,由于'|'左侧'a'的值,这总是有效的 would be stored in a register and then the assignment to 'a' would occur negating the effect on the assigned value for 'b'.
将被存储在寄存器中,然后分配给'a'将否定对'b'的指定值的影响。
int a = 5;
int b = -13;
b = a | (0 & (a = b));
You are modifying a variable and reading its value without an intervening sequence point. 您正在修改变量并读取其值而没有插入序列点。
b = a + 0 * (a = b);
// reading a's value modifying a
This is undefined behavior. 这是未定义的行为。 You have no right to any expectations on what the code will do.
您无权对代码的作用有任何期望。
The C/C++ compiler optimizes the expression 0 * (a = b)
to simply 0
which turns your code fragment into: C / C ++编译器将表达式
0 * (a = b)
为0
,将代码片段转换为:
int a = 5;
int b = -13;
b = a;
In C/C++, assigment are performed in the order of expression. 在C / C ++中,按表达顺序执行分配。 In Java, assignments occur last regardless of other expressions.
在Java中,无论其他表达式如何,分配都会在最后发生。
eg This increments in C but does nothing in Java. 例如,这在C中递增但在Java中没有任何作用。
a = a++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.