ohho
ohho

Reputation: 51951

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

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?

Upvotes: 25

Views: 3207

Answers (1)

trojanfoe
trojanfoe

Reputation: 122458

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;

Upvotes: 20

Related Questions