Is there any difference between the Java and C++ operators?

前端 未结 6 963
后悔当初
后悔当初 2021-01-12 00:16

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 precedence rules

相关标签:
6条回答
  • 2021-01-12 00:29

    I believe that operator precedence is consistent between C++ and Java and provided the expression is deterministic then it should evaluate the same way.

    0 讨论(0)
  • 2021-01-12 00:30
    • For an expression like:

      a = foo() + bar();
      

      In Java, the evaluation order is well-defined (left to right). C++ does not specify whether foo() or bar() 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.

    0 讨论(0)
  • 2021-01-12 00:35

    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.

    0 讨论(0)
  • 2021-01-12 00:37

    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.

    0 讨论(0)
  • 2021-01-12 00:39

    See this:

    int a = 0;

    int b = (a++) + (a);

    If you print b then it will output 0 in C++ whereas 1 in Java

    0 讨论(0)
  • 2021-01-12 00:42

    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++.

    0 讨论(0)
提交回复
热议问题