Factsheet
Why is the Elvis operator not more common? - Programming Language Design and Implementation Stack Exchange
Elvis operator
Elvis operator for Rust - language design - Rust Internals
What does ? do here?
Videos
So today I discovered that the elvis operator (for null coalescing) works in clang, and presumably in gcc as well (since it's apparently a gcc extension).
I'm not sure what other compilers this works in, but given that it's non-standard it's probably not a good idea to get too used to it, but what's wild to me is that it's not just a syntactic sugar - compared to the ternary operator it only evaluates the x from (x ?: y) once.
How widespread is compiler support for this operator? I've never had to use it in c++, but I've seen a lot of code using it in JS (which I've had to use a lot recently), so I imagine it's a useful construct.
Also, any other similar operators that's not well known?
Many popular mainstream languages that focus at least somewhat on conciseness have a similar operator, so I'd say that it is fairly common.
First, some notes:
- For the purposes of this answer, it doesn't matter whether the syntax is
?:,??,||oror, especially since all are equally concise. - What is a "true value" for this operator differs from language to language, and may not be the same as what is considered a "true value" in other contexts (like in an
ifcondition).
Now, let's go though some languages and see what we find:
- C and C++: no Elvis in the standards, since concise syntax sugar does not seem to be focus for these languages
- Java: Elvis was explicitly rejected, seemingly also because syntax sugar is not a focus for Java.
- C#:
??is anull-checking Elvis - Python:
orworks as truthy-checking Elvis - JavaScript:
||works as an Elvis operator that checks for truthiness,??is an Elvis operator that only checks fornullandundefined - PHP:
?:is a truthy-checking Elvis,??is anull-checking Elvis - Ruby:
||works as a truthy-checking Elvis - Go: no Elvis, since Go prefers simplicity of language to conciseness of code
- Swift:
??is anil-checking Elvis - Rust: no Elvis, presumably because Rust does not have concepts similar to truthiness or
null
Some languages simply don't have (a relevant type of) nulls, or don't have the concept of non-Boolean thruthiness, making it a not applicable feature.