I wrote following codes in java and C. But output of those programs are different. Java application gave 21 and C application gave 22 (I use GCC compiler).
Can you describe 开发者_如何学运维this ?
Here is the JAVA code.
class test
{
public static void main(String args[])
{
int a =5;
int b = (++a) + (++a) + (++a);
System.out.println(b);
}
}
Here is the C code.
#include <stdio.h>
int main( int argc, const char* argv[] )
{
int a =5;
int b = (++a) + (++a) + (++a);
printf("%d \n",b);
}
int b = (++a) + (++a) + (++a);
This is undefined behavior in C, which means it can output 21, 22, 42, it can crash or do whatever else it wants to. This is UB because the value of a scalar object is changed more than once within the same expression without intervening sequence points
The behavior is defined in Java because it has more sequence points. Here's an explanatory link
In Java evaluation is left to right, so the result is consistent. 6 + 7 + 8 == 21
精彩评论