1. Home
  2. Docs
  3. C Programming Guides
  4. Operators
  5. Conditional / Tenary Operator

Conditional / Tenary Operator

Introduction

Evaluates its first operand, and, if the resulting value is not equal to zero, evaluates its second operand. Otherwise, it evaluates its third operand.

Syntax

(condition) ? <true value> : <false value>

An example is given by

a = b ? c : d;

The above code is equivalent to

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

We can write multiple cases by nesting it.

a = (b == 0) ? c : (b == 1) ? d : e 

The above code can be visualized as

if (b == 0)
    a = c;
else if (b == 2)
    a = d;
else
    a = e;

Example Code

#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;
}
Was this article helpful to you? Yes No

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *