Hi people, when writing tests I stumbled upon this case
https://play.crystal-lang.org/#/r/ges0
Line 3 outputs true which is ok
But line 4 outpus 0 and I would expect 1
I certainly can understand a short circuit for && but not for ||
What do I miss here ?
You miss that 0
is not falsey like other languages. See Truthy and falsey values - Crystal.
2 Likes
That’s big surprise ;-)
Mmm it’s causing some problems, I need to find a solution…
1 Like
This C code behaves like I want, output is 1
#include <stdio.h>
int main() {
int a = 0;
int b = 3;
int r;
r = a || b;
printf("%d", r);
}
How one can mimic this behaviour in Crystal, given that a and b can be any integer values ?
How to write this the line r = a || b;
without casting a and b to some Bool
Edit : Answering myself, of course a cast is needed like in
when TypeOperator::AND
r = (l_lit != 0) && (r_lit != 0)
when TypeOperator::OR
r = (l_lit != 0) || (r_lit != 0)
A possibly more readable version could be:
r = !a.zero? || !b.zero?
Or even:
r = !(a.zero? && b.zero?)
Otherwise, as you’re edit indicates, you’ll need to convert the numbers to bools if you want to treat them like bools.
1 Like