I dont suppose there's any way to do logical and/or in C without coercing the result to 0 or 1?
I.e. `0 || 5` would result in 5, not 1
I dont suppose there's any way to do logical and/or in C without coercing the result to 0 or 1?
I.e. `0 || 5` would result in 5, not 1
@eniko What context is this in/which problem are you trying to solve?
Certainly, short-circuiting and non-booleans might have some low-level utility, but I'm not seeing it off-hand. I'm curious about what you need to do (although that might not help provide a better answer :(
@yo posted about it here: https://peoplemaking.games/@eniko/113220657017389342
@eniko your question is very interesting, thanks- I'm having fun poking with Godbolt and learning that && and || seem to always generate branching (gcc and clang, x86 and aarch64), and now I'm wondering why they would define them to always return 0 and 1 and not make it implementation-dependant.
(But then, I know nothing about C, so what do I know.)
@eniko you may have found https://cs.stackexchange.com/questions/155125/in-c-why-limit-and-to-evaluate-to-booleans already, which I found interesting (esp. the use of __typeof__ to define the macro).
@eniko Thanks, sorry I wasn't able to see that when I read the thread.
Sorry, I don't have much to contribute- I think because I still don't understand *why* C defines the operators to return 0 or 1, which I guess is the key. (I don't quite grasp clar fon's explanation.)
Thanks for giving us something interesting to think about! I'm getting into doing lower-level stuff progressively, and this is didactic.
@yo the reason C defines logical operators to return 0 or 1 is because they're boolean operations. now, C doesn't have a dedicated boolean type, but even without that wrapper this is still desirable behavior
for example take `(A && B) == (C && D)`
you would expect this to be true if A, B, C, and D are all non-zero. but the equality comparer in C just checks two numbers for equality. so even if they're all non-zero, if you don't coerce to 1 for true, this would return false (or 0) if B and D had different non-zero values
this is why you'll often see `!!x` in javascript, because this coerces a truthy value to a true boolean and a falsey value to a false boolean
@eniko oh, yeah; I would've thought not coercing to 0 and 1 could be better for performance, but being able to use == != intuitively is good, I guess.
I think we're just screwed that in the end, low-level booleans don't "exist" (or at least, they didn't in the past), so low-level programming languages are always going to have rough edges around booleans.
Thanks for the explanation!