Home > Blockchain >  Using empty char in C
Using empty char in C

Time:12-20

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 ?

CodePudding user response:

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" : ""
);

CodePudding user response:

OP: "I want to use the ternary operator..."
Unless the exercise is to practice the ternary operator, committing to a particular technique blinds one to possibilites.

The example below uses 'branchless' code to deliver a grammatically correct result (ignoring the American spelling of "neighbour".)

printf( "There %s %d neighbor%s\n",
    "are\0is"   (nbNeighbors == 1)*4,
    nbNeighbors,
    "s"   (nbNeighbors == 1) );

I'd never recommend manipulating the truth, but manipulating a truth value can come in handy sometimes.

EDIT
The above may be difficult for some to read/understand.

Below is the same thing expressed slightly differently:

printf( "There %s %d neighbor%s\n",
    !(nbNeighbors-1)*4   "are\0is",
    nbNeighbors,
    !(nbNeighbors-1)   "s" );

Tested, functional and branchless.

  • Related