# C Language Operators Conditional Operator/Ternary Operator

## Example

Evaluates its first operand, and, if the resulting value is not equal to zero, evaluates its second operand. Otherwise, it evaluates its third operand, as shown in the following example:

``````a = b ? c : d;
``````

is equivalent to:

``````if (b)
a = c;
else
a = d;
``````

This pseudo-code represents it : `condition ? value_if_true : value_if_false`. Each value can be the result of an evaluated expression.

``````int x = 5;
int y = 42;
printf("%i, %i\n", 1 ? x : y, 0 ? x : y); /* Outputs "5, 42" */
``````

The conditional operator can be nested. For example, the following code determines the bigger of three numbers:

``````big= a > b ? (a > c ? a : c)
: (b > c ? b : c);
``````

The following example writes even integers to one file and odd integers to another file:

``````#include<stdio.h>

int main()
{
FILE *even, *odds;
int n = 10;
size_t k = 0;

even = fopen("even.txt", "w");
odds = fopen("odds.txt", "w");

for(k = 1; k < n + 1; k++)
{
k%2==0 ? fprintf(even, "\t%5d\n", k)
: fprintf(odds, "\t%5d\n", k);
}
fclose(even);
fclose(odds);

return 0;
}
``````

The conditional operator associates from right to left. Consider the following:

``````exp1 ? exp2 : exp3 ? exp4 : exp5
``````

As the association is from right to left, the above expression is evaluated as

``````exp1 ? exp2 : ( exp3 ? exp4 : exp5 )
`````` PDF - Download C Language for free
{"ft_lang_label":"__label__en","ft_lang_prob":0.7297601,"math_prob":0.99045765,"size":1222,"snap":"2021-43-2021-49","text_gpt3_token_len":371,"char_repetition_ratio":0.09934319,"word_repetition_ratio":0.008474576,"special_character_ratio":0.3535188,"punctuation_ratio":0.25964913,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9988036,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-19T16:20:32Z\",\"WARC-Record-ID\":\"<urn:uuid:a4dbf32a-e775-4587-87ad-471e3eb64222>\",\"Content-Length\":\"47035\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:a93d7ab5-6b9a-4209-b881-8d2845c509cb>\",\"WARC-Concurrent-To\":\"<urn:uuid:f001578e-1eef-4469-af60-6f303be2ea7a>\",\"WARC-IP-Address\":\"40.83.160.29\",\"WARC-Target-URI\":\"https://riptutorial.com/c/example/2158/conditional-operator-ternary-operator\",\"WARC-Payload-Digest\":\"sha1:OI26H7HYCS5JZEF2YOP3KVDYQHGNIUIC\",\"WARC-Block-Digest\":\"sha1:TWW5ZDOVBJAINUJQSAWVAVT44OVDPXNB\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323585270.40_warc_CC-MAIN-20211019140046-20211019170046-00113.warc.gz\"}"}