×

Conditional Operator in C

In C programming language, the conditional operator (also known as the ternary operator) is a shorthand way of writing an if-else statement. The syntax of conditional operator in C is given below:

Syntax:

condition ? expression1: expression2

If the condition is true, the operator returns expression1, otherwise it returns expression2.

Here is an example:

int x = 5, y = 10;
int min = (x < y) ? x : y;

In this example, the variable min will be assigned the value of x (5) because 5 is less than 10.

It can also be used in an expression as:

printf("%d", (x>y)? x:y);
It will print the value of x if x>y else y.

This statement is equivalent to the following if-else statement:

if (a > b) {
larger = a;
} else {
larger = b;
}

Note: It is important to note that the ternary operator can only return one value and the type of the expressions on both side of the : operator should be same.

Working of Conditional operator in C

The conditional operator in C works by evaluating the condition specified before the ? operator. If the condition is true, the expression following the ? operator is executed and its value is returned. If the condition is false, the expression following the : operator is executed and its value is returned.

Here is the step-by-step process of how the conditional operator works in the example we provided earlier:

  • The program declares an int variable age and assigns it the value of 20.
  • The program declares a pointer to char variable status and assigns it the value of "adult" if the value of age is greater than or equal to 21, or "minor" if the value of age is less than 21.
  • The program evaluates the condition age >= 21 which is false in this case.
  • Since the condition is false, the expression "minor" following the : operator is executed.
  • The value of "minor" is returned and assigned to the variable status.
  • The program then prints the value of status using the printf() function.

It is important to note that the conditional operator is a shorthand way of writing an if-else statement, and it can be used to assign a value to a variable, execute a statement or return a value.

Here is an example of using the conditional operator in a program.

Example:

#include <stdio.h>
int main() {
int age = 20;
char *status;
status = (age >= 21) ? "adult" : "minor";
printf("You are a %s\n", status);
return 0;
}

Output:

You are a minor

In this example, the program first declares an int variable age and assigns it the value of 20. It then declares a pointer to char variable status and assigns it the value of "adult" if the value of age is greater than or equal to 21, or "minor" if the value of age is less than 21. The program then prints the value of status using the printf() function.

Difference between Conditional Operator in C and if-else Statement

The conditional operator (? :) and the if-else statements are both used to make decisions in C, but they have some key differences:

  • Syntax: The conditional operator has a shorthand syntax, which is often more concise than an if-else statement. The if-else statement has a more verbose syntax that requires the use of curly braces {} and the keywords if, else, and else if.
  • Evaluation: The conditional operator evaluates a single condition and returns a value or executes a single statement based on the outcome of that condition. On the other hand, an if-else statement can evaluate multiple conditions using else if and can execute multiple statements based on the outcome of those conditions.
  • Type of returned value: The conditional operator can only return one value and the type of the expressions on both side of the : operator should be same. The if-else statement doesn't return any value.
  • Nesting: The conditional operator cannot be nested within another conditional operator or if-else statement. On the other hand, if-else statements can be nested within other if-else statements to create more complex decision-making logic.
  • Execution of statement: The conditional operator will execute only one statement, whereas if-else statement can execute multiple statements based on the conditions.

In general, the conditional operator is best used for simple decisions that only require a single condition to be evaluated, and it is often used to assign a value to a variable based on that condition. The if-else statement is more powerful and flexible, and it is best used for more complex decision-making logic that requires multiple conditions to be evaluated and multiple statements to be executed based on those conditions.


Related Topics

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it...

3 minutes read.

How to initialize array to zero in C

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

3 minutes read.

Difference between Scope and Lifetime in C

In this article, we will discuss about the key differences between scope and lifetime in C, including their definitions, applications, and how they relate to one another. By the end...

8 minutes read.

Difference between rand() and srand() function in C

What is the rand()?The rand() means random function. This function is used in C. It generates random numbers in the range of 0 to the RAND_MAX. Suppose we generate a...

3 minutes read.

Range of int in C

In this session we know about the rage of the int in C language with the suitable examples and the programs. Firstly, we can learn the range of int: The int is...

3 minutes read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

How to Avoid Structure Padding in C

Generally, when an object of some structure type is declared, some contiguous memory will be allocated in block form, which will be allocated to structure members. To understand structure padding...

3 minutes read.

Inline Function in C

Inline Function in C A normal function will become an inline function when the function prototype of that function is prepended with the keyword "inline". Inline functions are the function where...

4 minutes read.

Free() Function in C

Free() function is a built-in function which is define in the stdlib.h header file. If we want to use this function in our program, we must include the stdlib.h header...

4 minutes read.

Decimal to Hexadecimal in C

Decimal to Hexadecimal in C Let us first understand the definitions of decimal and hexadecimal. In algebra, a decimal number is defined as a number whose whole number part and a...

3 minutes read.

Data Types in C

Data type is a very important concept in C programming language. Simply, “A data type is the classification of data values that a data item can have.” We need to...

11 minutes read.

Pyramid Pattern in C

Pyramid Pattern in C A pyramid is a polyhedron created by connecting a base that will be a polygon, and all the lateral faces are triangles. All the bases are connected...

5 minutes read.

Find out Power without using POW function in C

Introduction: In this discussion, we will discuss how we find out power without using the POW function in C. In this article, you'll understand how to compute integer powers in...

3 minutes read.

Continue in C

C language: C language is a procedure oriented programming language. We can say that it is a platform dependent language. C language is introduced by Dennis Ritchie in the year 1970. We...

2 minutes read.

How to create a binary file in C?

Creating a binary file in C language is very simple, requiring only some specific functions to be implemented. There are also other binary modes: read, and write, which will be...

7 minutes read.

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 minutes read.

How to lock top row in Excel

How to lock top row in excel While working with an Excel spreadsheet, the user utilizes the rows and columns to enter the details under various headings. Sometimes while scrolling the...

4 minutes read.

Double Specifier in C

What is a double specifier? The term double denotes the double data type in C. It more accurately depicts floating point numbers. The idea that it has twice the precision of...

3 minutes read.

GCD of Two Numbers in C

The GCD means the greatest common divisor of two or more integers, it is also called as hcf. The gcd returns the greatest integer of the given two integers that...

3 minutes read.

#undef in C

#undef in C In the C programming language, the #undef directive is used to undefine the macro or any constant, which will be defined by the preprocessor directive #define. The #undef...

3 minutes read.