6

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?

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
Oxdeadbeef
  • 1,033
  • 2
  • 11
  • 26

1 Answers1

11

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.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431