7 ms·
In Objective-C (and some other languages with ternary operators) the same can be written like this: int a = b ?: c ?: 0
by accatyyc 7y ago
In Objective-C (and some other languages with ternary operators) the same can be written like this:
int a = b ?: c ?: 0
- ChrisMarshallNY 7y agoYup. Personally, I like the ternary operator, and I also like the nil-coalescing operator, but I'm quite aware that they can produce difficult-to-maintain code, so I'm careful with them. I have gone and done some silly stuff with both, but then, I realized that I was leaving unmaintainable code. If you use godbolt.org, you can actually see what code is produced by the source.
- messe 7y agoThe second conditional is unneeded as the 0 will only be returned if c evaluates to 0, so it can equally well be written int a = b ?: c;
- WWLink 7y agoThat one's straight up called the Elvis Operator. I hate it when things like this get names that everyone's supposed to know and it's considered a mark against you if you've never heard it before, but I do think the name Elvis Operator is hilarious. :D
- toxik 7y agoI was wondering why the funny name, and > The name "Elvis operator" refers to the fact that when its common notation, ?:, is viewed sideways, it resembles an emoticon of Elvis Presley. https://en.wikipedia.org/wiki/Elvis_operator https://en.wikipedia.org/wiki/Elvis_operator
- deleted 7y ago[deleted]
- pflats 7y agoAlso, a lot of other languages (Python, Ruby, JS, etc.) can do the same thing with their OR operator: b = list.next.to_s || "Reached end of list." If list.next.to_s is non-nil, then the OR statement is short-circuited and list.next.to_s will be assigned to b. If b is nil and "Reached end of list." is non-nil, then OR statement will return the string literal to be assigned to b instead. Thus, a = b || c || 0 would be the equivalent for those languages. edit: One BIG downside to this I forgot to mention at first: If nil and a false value are both possible for a variable, then this construction can betray you and break your heart.
- DerekL 7y agoThat's not specific to Objective-C, it's a GCC extension to the C language.
- saagarjha 7y ago(Which Clang happens to support, hence it working here.)