A new C idiom
Posted by kernelbob on December 10, 2008
I’ve been writing C since 1981. I haven’t come up with a new idiom in a decade, until this morning.
Have you ever written something like this?
printf("You have %d grapes.\n", grape_count);
It works fine until you have a singleton grape. Then it prints,
You have one grapes.
The traditional workaround is something like this.
printf("You have %d grape%s.\n",grape_count, grape_count == 1 ? "" : "s");
But this morning I wrote something different.
printf("You have %d grape%s.\n", grape_count, &"s"[grape_count == 1]);
Old dogs. (C, not me!) New tricks. Once in a while.
(Insert standard disclaimer about how this is not internationalized.)