views:

255

answers:

3

Booleans seem to be the most primitive building blocks of programming languages, because they can actually take only two (or in some cases three) "singleton" values: true, false (and sometimes undeterminded/null)

But it seems that sometimes language design might allow someone to write code where actually "true is false" or "true is not true". I usually thought that this only applies to weakly typed languages, where (inconsistent) implicit conversions will result in "true==false", like in this case. But actually this problem might arise in more strong typed languages, like in C++.

The question is how can you do this kind of anomaly in your programming language? I'm more interested in languages that have strong typing, because there it should be harder to do this (if it's not impossible). I'd actually be surprised, if this anomaly could be reproduced in logical programming languages, like Prolog.

+2  A: 

In Java:

Boolean true1 = new Boolean(true);
Boolean true2 = new Boolean(true);
System.out.println("true == true: " + (true1 == true2));

The reason why this prints false is that == checks for object identity. And although the two Boolean objects represent the same value (true) they are two separate objects.

Also note that there is almost never a valid reason to use that Boolean constructor. When one uses Boolen.TRUE, Boolean.FALSE and Boolean.valueOf() exclusively then this kind of problem can't happen.

Joachim Sauer
Interestingly enough, if it was `Boolean true1 = Boolean.valueOf(true);` and the same for true2, the result would be `true`.. :)
Aviad Ben Dov
A: 

Well, in some strongly typed languages, such as Perl and LPC, there is no specific Boolean type or value set, with more general classes of value being used for Boolean logic. So then it's easy to have different true values that aren't strictly equivalent to each other, and sometimes different false values. (That's true for Perl, not for LPC.)

chaos
A: 

But actually this problem might arise in more strong typed languages, like in C++.

The link you provided about C++ talks about an undefined behavior. So, technically this works but it is not correct!

Anyway,

int x = 3;

if(1 < x > 2)
    std::cout << "This line will not be printed";

First, this expression will be evaluated into true, then it will be implicitly converted to the integer 1.

1 < x // true == 1

Then, the whole expression will evaluate into false.

1 < x > 2 // true > 2 == 1 > 2 !!!
AraK