Conditional Operators in C Programming

Conditional Operators

The conditional expression can be used as shorthand for some if-else statements. It is a ternary operator. This operator consists of two symbols: the question mark (?) and the colon (:).

The general syntax of the conditional operator is:
Identifier = (test expression)? Expression1: Expression2 ;

This is an expression, not a statement, so it represents a value. The operator works by evaluating test expression. If it is true (non-zero), it evaluates and returns expression1. Otherwise, it evaluates and returns expression2.

The classic example of the ternary operator is to return the smaller of two variables. Every once in a while, the following form is just what you needed. Instead of...

if (x < y) 
{
min = x;
}
else
{
min = y;
}
	

You just say...

 
	min = (x < y) ? x : y;
	

Suppose that x and y are integer variables whose values are 100 and 4, respectively. After executing above statement, the value of min is 4.

This is the only operator in C that makes use of three operands. It tests condition corresponding to the test expression, if it is true the value corresponds to Expression1 and if it is false it corresponds to the value of Expression2.

Example:

Ready to get started?

Ready to embark on your journey into the world of C programming? Our comprehensive course provides the perfect starting point for learners of all levels. With engaging lessons, hands-on exercises, and expert guidance, you'll gain the skills and confidence needed to excel in this fundamental programming language. Let's dive in and unlock the endless possibilities of C programming together!