I'm surprised string plus boolean has similar effect of ternary operation:
int apple = 2;
printf("apple%s\n", "s" + (apple <= 1));
If apple <= 1
, it will print apple. Why does this work?
Because the condition evaluates to either 0 or 1, and the string "s"
contains exactly one character before the 0-terminator. So "s" + bool
will evaluate to the address of "s"
if bool
is false, and to one character behind that, the address of the 0-terminator if true.
It's a cool hack, but don't ever use code like that in earnest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With