Search code examples
cstringbooleanplural

const string plus boolean to pluralize in C


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?


Solution

  • 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.