Conditional Operator In C++ Wit Example

Card image cap

Conditional Operators ?

The conditional operator is an operator used in C and C++ as well as in other languages also, operator returns one of two values depending on the result of an expression.


Syntax of Conditional Operator ?

(expression 1) ? expression 2 : expression 3

If expression 1 evaluates to true, then expression 2 is evaluated.(or)
If expression 1 evaluates to false, then expression 3 is evaluated instead.


Conditional Operators

Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus a%b

Card image cap

Example 1:

#define MAX(a, b) (((a) > (b)) ? (a) : (b))

#define MAX(a, b) (((a) > (b)) ? (a) : (b))
In this example, the expressiona > b is evaluated. If it evaluates to true then a is returned. If it evaluates to false, b is returned. Therefore, the line MAX(4, 12); evaluates to 12.


Example 2:



Output:

 result of x: 40
Card image cap

Example 3:



Output:

First run:
Enter year: 2000
2000 is Leap year.

Second run:
Enter year: 2017
2017 is not a Leap year.

Third run:
Enter year: 1900
1900 is not a Leap year.

Fourth run:
Enter year: 2016
2016 is Leap year.


Example 4:



Output:

Enter year (ENTER 0 for exit...): 2000
2000 is Leap year.

Enter year (ENTER 0 for exit...): 2017
2017 is not a Leap year.

Enter year (ENTER 0 for exit...): 1900
1900 is not a Leap year.

Enter year (ENTER 0 for exit...): 2016
2016 is Leap year.

Enter year (ENTER 0 for exit...): 0 
0 is Leap year.
Card image cap