Conditional Assignments

Sometimes, you’ll have a scenario with two variables, and you need to use one of them based on a simple test. Rather than a long and awkward if / else statement, C allows the use of the ? : form. It is perfectly acceptable to write:

int i,j,k,l;
i = (j > 5? k : l)

which will set i to k if j is greater than 5, and l otherwise.
Another common use is [sf]?printf statements:

printf("The test %s\n",(status == OK) ? "passed" : "failed");

However, one can’t use it to handle selective assignments. The following code is illegal:

int i,j,k;
((i>5) ? j : k) = 5;

This cannot be used to choose whether j or k is set to 5.
There is, however a way this can be done. Using pointer, we can select which one to deference:

*((i>5) ? &j : &k) = 5;

This will work.

2 responses to “Conditional Assignments”

  1. Do you ever actually use the famous trinary operator
    … in code that anyone else is going to read/maintain?

    I’m no big-time C hacker, but C++ code is a major part of my job, and it seems to me that if/else is a great deal more readable, even for little one- or two-liners. The main utilities of ?/:, it seems to me, are to help you save a few bytes on the hard drive where you keep your code and to keep the ? and : characters from feeling bad for being left out of the language specification.

  2. I use it (then again, I’m a big time C hacker ).

    This little trick is rather useless, I admit, but a fun piece of trivia (I’m interviewing some students now for a position, and so I’ve been collecting fun bits of trivial trivia). If you prefer if/else, be my guest… it is a little more readable, but sometimes, you have a long and complex statement that you really don’t want to rewrite, or a print statement that needs some text:

    max = (i>j) ? i : j;

    instead of:

    if (i>j)
      max = i;
      max = j;

    I assume you also prefer brackets, which means you might have:

    if (i>j) {
      max = i;
    } else {
      max = j;

    Is that really better? Sometimes, cleaner code is when you can see the entire thing on one screen, instead of having a really long spread out function.

    Also, compare:

    if (0 == stat) {
      printf("Test number %d (input parameters %d, %04X, %6f) passed (status code %d)\n",index, foo, bar, fubar, stat);
    } else {
      printf("Test number %d (input parameters %d, %04X, %6f) failed (status code %d)\n",index, foo, bar, fubar, stat);


    printf("Test number %d (input parameters %d, %04X, %6f) %s (status code %d)\n",index, foo, bar, fubar, (0 == stat) ? "passed" : "failed", stat);

Leave a Reply

Your email address will not be published. Required fields are marked *