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;
}
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;
}
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;
}
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;
}
This is usually called a null-coalescing operator, and exists in other languages too, like JavaScript and C#.
Top comments (2)
Two things:
?:
is not accepted by the dotnet compiler, so in all lights this does not apply to C#.??
It is used like this:
It is right there in the very last link in your article.
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??
.