Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the shorten question mark colon ?: a Objective-C syntax?

Tags:

Xcode does not give an error of my (thought-to-be) typo:

 NSString *theme = [[NSUserDefaults standardUserDefaults] objectForKey:@"theme"];  NSLog(@"Theme: %@", theme ?: @"Default"); 

It turns out:

 NSLog(@"Theme: %@", theme ?: @"Default"); 

works same as:

 NSLog(@"Theme: %@", theme ? theme : @"Default"); 

Is the above shorten syntax good for gcc only? Or it is part of Objective-C?

like image 429
ohho Avatar asked Oct 25 '12 09:10

ohho


People also ask

What does question mark and colon mean in C?

As everyone referred that, It is a way of representing conditional operator if (condition){ true } else { false }

What is the question mark operator in C?

The question mark operator, ?:, is also found in C++. Some people call it the ternary operator because it is the only operator in C++ (and Java) that takes three operands. If you are not familiar with it, it's works like an if-else, but combines operators.

What does question mark mean in programming?

“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false. The evaluation of the condition should result in either true/false or a boolean value.

What is the other name for (? :) question mark and colon operator?

?: = Question Mark Colon is also called C Ternary Operator.


1 Answers

It's a GNU extension to the conditional expression in C:

From here:

A GNU extension to C allows omitting the second operand, and using implicitly the first operand as the second also:

a = x ? : y; 
like image 79
trojanfoe Avatar answered Nov 02 '22 05:11

trojanfoe