Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this boolean compile in C++ and not in Java?

Tags:

java

c++

In C++, this expression will compile, and when ran, will print test:

    if(!1 >= 0) cout<<"test";

but in Java, this will not compile:

    if(!1 >= 0) System.out.println("test");

and instead parentheses are needed:

    if(!(1>=0)) System.out.println("test");

but test will not print since 1 >= 0 is true, and NOT true is false.

So why does it compile AND print out test in C++, even though the statement is false, but not in Java?

Thanks for your help.

like image 528
qwertyuiop5040 Avatar asked Oct 23 '13 05:10

qwertyuiop5040


2 Answers

This occurs because !1 is valid in C++ but not in Java1.

Both languages parse !1>=0 as (!1)>=0 because (in both C+ and Java) ! has as higher precedence than >=.

So (in C++), (!1)>=0-> 0>=0 -> true but (in Java) !1 (!int) is a type error.

However (in either C++ or Java), !(1>=0) -> !(true) -> false.


1 Java only defines the ! operator over the boolean type.

like image 82
user2864740 Avatar answered Sep 20 '22 17:09

user2864740


In java unary operator ! has high precedence than conditional operator >=. That why it needs parenthesis ().

Here is the details table of operator precedence of Java.

But, In C++ positive value in condition refer as boolean true value. So, if(!1>=0) is valid in C++ but invalid in Java. In Java, boolean value is only true and false. It never treat positive value as true.

like image 42
Masudul Avatar answered Sep 21 '22 17:09

Masudul