If you take Java's primitive numeric types, plus boolean, and compare it to C++ equivalent types, is there any difference what concerns the operators, like precedenc开发者_开发百科e rules or what the bit-manipulation operators do? Or the effect of parenthesis?
Asked another way, if I took a Java expression and tried to compile and run it in C++, would it always compile and always give the same result?
For an expression like:
a = foo() + bar();
In Java, the evaluation order is well-defined (left to right). C++ does not specify whether
foo()
orbar()
is evaluated first.Stuff like:
i = i++;
is undefined in C++, but again well-defined in Java.
In C++, performing right-shifts on negative numbers is implementation-defined/undefined; whereas in Java it is well-defined.
Also, in C++, the operators
&
,|
and^
are purely bitwise operators. In Java, they can be bitwise or logical operators, depending on the context.
Java specifies more about the order of evaluation of expressions than C++, and C++ says that you get undefined behavior if any of the legal evaluation orders of your expression modify an object twice between sequence points.
So, i++ + i++
is well defined in Java, but has undefined behavior (no diagnosis required) in C++. Therefore you can't blindly copy expressions from Java to C++.
For bitwise operators, Java specifies two's-complement representation of negative numbers whereas C++ doesn't. Not that you're likely to encounter another representation in C++, but if you did then you would find for example that -2 | 1
is always -1
in Java, but is -2
in a C++ implementation using 1s' complement.
I believe that operator precedence is consistent between C++ and Java and provided the expression is deterministic then it should evaluate the same way.
The right-shift operator >>
is different. In Java it's always an arithmetic shift, i.e. it copies the sign bit into the leftmost bit, whereas in C++ it's implementation-defined whether it's an arithmetic or logical shift. You can get a logical shift in Java using >>>
, which doesn't exist in C++.
See this:
int a = 0;
int b = (a++) + (a);
If you print b
then it will output 0
in C++ whereas 1
in Java
There must be lot of difference, because in Java almost all numeric types are always signed. Read Java Puzzlers book and Java Language Specification to understand all the subtle differences.
精彩评论