Search code examples
ccharprintfternary

Using empty char in C


I want to use the ternary operator and an empty char '' to spell correctly the word "neightbor" (with or without a "s").

I want to do the following :

printf("There is %d neightbor%c\n", nbNeighbors,  (nbNeighbors>1)?'s':'');

obviously, I get an arror error: empty character constant

How can I menage to use this trick to get the right spelling in one printf ?


Solution

  • You could use a non-printable character but they may end up looking like something else.

    You'd be better off using strings:

    printf("There %s %d neighbor%s\n",
     nbNeighbors != 1 ? "are" : "is",
     nbNeighbors,
     nbNeighbors != 1 ? "s" : ""
    );