DEV Community

Michael Scovetta
Michael Scovetta

Posted on

C's Ternary Operator

#c

I first learned to program in C when I was 14 or 15, and in the decades since, I've used the ternary operator often enough. It's convenient in cases like:

#include <stdio.h>
#include <stdlib.h>

int main() {
  bool is_admin = check_admin();
  set_level(is_admin ? 999 : 1);
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

The ternary operator works the same if you had written:

#include <stdio.h>
#include <stdlib.h>

int main() {
  bool is_admin = check_admin();
  if (is_admin) {
    set_level(999);
  } else {
    set_level(1);
  }
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

I came across another form of this operator, which I don't recall ever seeing before, and wanted to share. As it turns out, this is a GNU extension. You can omit the statement between the ? and the : entirely, and the operator changes a bit, returning either the value before the operator if it isn't false, null, or zero, or the value after it otherwise.

#include <stdio.h>
#include <stdlib.h>

int main() {
  char* temp_dir = getenv("TEMPDIR") ?:
                   getenv("TMPDIR") ?:
                   getenv("TEMP") ?:
                   "/tmp";
  printf("Temp dir is: %s", temp_dir);
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

This is essentially the same as:

#include <stdio.h>
#include <stdlib.h>

int main() {
  char* temp_dir = getenv("TEMPDIR");
  if (temp_dir == NULL)
    temp_dir = getenv("TMPDIR");
  if (temp_dir == NULL)
    temp_dir = getenv("TEMP");
  if (temp_dir == null)
    temp_dir = "/tmp";

  printf("Temp dir is: %s", temp_dir);
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

This is usually called a null-coalescing operator, and exists in other languages too, like JavaScript and C#.

Top comments (2)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

Two things:

  1. ?: is not accepted by the dotnet compiler, so in all lights this does not apply to C#.
  2. The null-coalescing operator in C# is this one: ??

It is used like this:

    string test = null;
    test = test ?? Environment.GetEnvironmentVariable("TMPDIR");
    // OR:
    test ??= Environment.GetEnvironmentVariable("TMPDIR");
Enter fullscreen mode Exit fullscreen mode

It is right there in the very last link in your article.

Collapse
 
scovetta profile image
Michael Scovetta

Thanks José! You're absolutely correct. ?: is specific to the GNU extension (though I suppose other languages might also use it). In C# it's ??.