## Conditional Expressions in C

**By:** Emiley J

if (a > b) z = a; else z = b;compute in

`z`the maximum of

`a`and

`b`. The

*conditional expression*, written with the ternary operator ``

`?:`'', provides an alternate way to write this and similar constructions. In the expression

the expressionexpr?_{1}expr:_{2}expr_{3}

*expr*is evaluated first. If it is non-zero (true), then the expression

_{1}*expr*is evaluated, and that is the value of the conditional expression. Otherwise

_{2}*expr*is evaluated, and that is the value. Only one of

_{3}*expr*and

_{2}*expr*is evaluated. Thus to set

_{3}`z`to the maximum of

`a`and

`b`,

z = (a > b) ? a : b; /* z = max(a, b) */It should be noted that the conditional expression is indeed an expression, and it can be used wherever any other expression can be. If

*expr*and

_{2}*expr*are of different types, the type of the result is determined by the conversion rules discussed earlier in this chapter. For example, if

_{3}`f`is a

`float`and

`n`an

`int`, then the expression

(n > 0) ? f : nis of type

`float`regardless of whether

`n`is positive.

Parentheses are not necessary around the first expression of a conditional
expression, since the precedence of `?:` is very low, just above
assignment. They are advisable anyway, however, since they make the condition
part of the expression easier to see.

The conditional expression often leads to succinct code. For example, this
loop prints `n` elements of an array, 10 per line, with each column
separated by one blank, and with each line (including the last) terminated by a
newline.

for (i = 0; i < n; i++) printf("%6d%c", a[i], (i%10==9 || i==n-1) ? '\n' : ' ');A newline is printed after every tenth element, and after the

`n`-th. All other elements are followed by one blank. This might look tricky, but it's more compact than the equivalent

`if-else`. Another good example is

printf("You have %d items%s.\n", n, n==1 ? "" : "s");

Comment on this tutorial

- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview

#### categories

#### Subscribe to Tutorials

#### Related Tutorials

Sum of the elements of an array in C

Printing a simple histogram in C

Find square and square root for a given number in C

Simple arithmetic calculations in C

Passing double value to a function in C

Passing pointer to a function in C

Infix to Prefix And Postfix in C

while, do while and for loops in C