Bobbing for Kernels

See Bob. See Bob bob. Bob, Bob, bob!

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

2 Responses to “A new C idiom”

  1. […] bfpower wrote an interesting post today onHere’s a quick excerpt 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.) […]

  2. Mig said

    always is good to have multiple ways to do the same.

    Great idea.

Leave a comment