Conditional Operator
The conditional operator (?:), also known as the ternary operator, is an operator that evaluates an condition and results in one of two values depending on whether the condition was truthy or falsey
condition?v1:v2
if condition is truthy, expression evaluates to v1, otherwise it evalues to v2.
This makes it seem like it is an operator way to do if/else.. but that is not how this operator is used. One of the most common mistakes in using this operator is to treat it as if it is an if statement. The conditional operator is NOT A SHORTHAND IF ELSE!
Here is an example of how NOT to use the operator which is to use it like an if/else. This program asks user to enter a number and prints out whether it is positive or not positive.
// DO NOT USE ?: operator like this!
#include <stdio.h>
int main(void)
{
int number;
printf("enter a number: ");
scanf("%d", &number);
//this is WRONG!!! DO NOT USE ?: this way!
(number > 0) ? printf("%d is positive\n",number) : printf("%d is not positive\n",number);
return 0;
}
Instead of treating it like if/else we need to treat it as an expression and use the results of the operator in instead.
In this version, of the same program, the conditional operator evaluates either to "positive" or "not positive". There is no "action" within the conditional.. just a result. That result is then printed by the printf() function at the %s format code. This is not the same as the previous.
#include <stdio.h>
int main(void)
{
int number;
printf("enter a number: ");
scanf("%d", &number);
printf("%d is %s\n",number, (number > 0)? "positive": "not positive");
return 0;
}
The difference is subtle but important. If you want to use ?:, make sure you use it properly.