Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 736
Oxdeadbeef Avatar asked Jul 01 '12 00:07

Oxdeadbeef


1 Answers

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.

like image 77
Daniel Fischer Avatar answered Sep 30 '22 10:09

Daniel Fischer