Const string plus boolean for pluralization in C

I am surprised that the plus boolean line has a similar triple operation effect:

int apple = 2; printf("apple%s\n", "s" + (apple <= 1)); 

If apple <= 1 , it will print an apple. Why does it work?

+6
source share
1 answer

Since the condition evaluates to 0 or 1, and the string "s" contains exactly one character before the 0-terminator. Thus, "s" + bool will evaluate the address of "s" if bool is false, and to one character after it, the address of the 0-terminator if true.

This is a cool hack, but never use this code seriously.

+11
source

Source: https://habr.com/ru/post/919405/


All Articles