×

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

memcpy() in C

Introduction: Here we discuss about the memcpy() function in C. The memcpy() function is also called the Copy Memory Block function. Used to create a copy of a specific drawing...

4 minutes read.

Stack implementation in C

Stack implementation in C Stack stores the data in a particular order. It is a linear data structure that follows the principle of the Last In First Out (LIFO) technique where...

3 minutes read.

C vs Java Strings

String in C In C, we can define a string as a bunch of characters. A character array is distinguished from a string by the presence of the special character '\0'...

5 minutes read.

Errors in C

Errors in C Errors are nothing but problems or faults that pretty much occur in all the programming languages. Errors make the behavior of the program seem abnormal, and even the...

4 minutes read.

Find the Largest Three Distinct Elements in an Array using C/C++

In this tutorial, we will demonstrate how to use a C/C++ programme to locate the highest three different elements in an array. C/C++ Program to Find the Largest Three Different Elements...

3 minutes read.

How to use sine() function in C

What is Function? The function is a set of statements. It takes input and performs some computation to produce output. The process is a set of codes only achieved when it is...

3 minutes read.

Floyd’s triangle in C

Floyd’s triangle in C Floyd’s triangle is named after a person Robert Floyd. It is a right-angled triangle that is of natural numbers starting from 1 and consecutively selects the upcoming...

4 minutes read.

C Programming Tutorial

What is C Programming C is most popular and widely used computer programming language. It was developed by Dennis Ritchie in 1972 at the Bell Lab. It is used to develop system application software. There...

8 minutes read.

Why C is a middle level language

The C programming language is generally referred to as a high level language but we glance through the backend of C, i.e the working of C as a programming language...

4 minutes read.

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.

Add two numbers using the function in C

Here we will learn how to add two numbers by creating function in C. Let’s learn this with help of example. Code: - #include <stdio.h> int add_two_no(int a, int b); int main(){   int first_num,...

1 minute 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.

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.

Prime Number code in C

Prime Number Programs in C language In this tutorial, we will learn how to check whether the given number is a prime number or not, and how to print all the...

4 minutes read.

C Program to Find the Largest Number using Ternary Operator

In this tutorial, we will write some program to determine which of the provided integers is larger using the ternary operator, also known as the conditional operator in C. Ternary Operator: The ternary...

3 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.

Pointer arithmetic in C

In the C programming language, a pointer is an address which stores a numeric value. Hence, a developer can perform several arithmetic operations on the same just as one does...

4 minutes read.

Difference between while and for loop in C

While Loop The syntax that can be used for the ‘while’ loop in the C programming language is mentioned below: while (test expression or termination condition)  {   // the main body of the...

6 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.

Character Set in C

Introduction Every language has some basic elements which are used to represent information. The English language includes alphabets which together shape a sentence, after which the sentences are used to shape...

3 minutes read.