Evan Fishback Evan Fishback - 6 months ago 33
C Question

C programming: Conditional Operators why is this code snippet right?

I am currently reading a book on Objective-C/C programming with an iOS focus and was presented with this code snippet:

int i = 20;
int j = 25;
int k = ( i > j) ? 10 : 5;

if (5 < j - k ) { // Frist Expression
printf("The first expression is true.");
} else if ( j > i ) { // Second Expression
printf("The second expression is true.");
} else {
printf("Neither is true.");

"What will be printed to the console?"

Before putting this into Xcode to verify my answer I came up with my own, which turned out to be wrong.
The console displayed that "The first expression is true."

Why is this the case? Specifically the ? conditional operator does the 10 in 10:5 mean true and 5 mean false?


Conditional Operator (Ternary Operator)


So if condition is true then TrueExp will be returned and if condition is false, FalseExp will be returned.

In your case,(i>j) means (20>25) which is false and so it returns 5.