Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, certification courses.

Created with over a decade of experience and thousands of feedback.

C Introduction

  • Getting Started with C
  • Your First C Program

C Fundamentals

  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)

C Programming Operators

C Flow Control

C if...else Statement

  • C while and do...while Loop
  • C break and continue

C switch Statement

  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples
  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

C Structure and Union

  • C structs and Pointers
  • C Structure and Function

C Programming Files

  • C File Handling
  • C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Check Whether a Number is Even or Odd
  • Make a Simple Calculator Using switch...case
  • Find LCM of two Numbers

C Ternary Operator

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false . For example,

Here, when the age is greater than or equal to 18 , Can Vote is printed. Otherwise, Cannot Vote is printed.

Syntax of Ternary Operator

The syntax of ternary operator is:

The testCondition is a boolean expression that results in either true or false . If the condition is

  • true - expression1 (before the colon) is executed
  • false - expression2 (after the colon) is executed

The ternary operator takes 3 operands (condition, expression1 and expression2) . Hence, the name ternary operator .

Example: C Ternary Operator

In the above example, we have used a ternary operator that checks whether a user can vote or not based on the input value. Here,

  • age >= 18 - test condition that checks if input value is greater or equal to 18
  • printf("You can vote") - expression1 that is executed if condition is true
  • printf("You cannot vote") - expression2 that is executed if condition is false

Here, the user inputs 12 , so the condition becomes false . Hence, we get You cannot vote as output.

This time the input value is 24 which is greater than 18 . Hence, we get You can vote as output.

Assign the ternary operator to a variable

In C programming, we can also assign the expression of the ternary operator to a variable. For example,

Here, if the test condition is true , expression1 will be assigned to the variable. Otherwise, expression2 will be assigned.

Let's see an example.

In the above example, the test condition (operator == '+') will always be true . So, the first expression before the colon i.e the summation of two integers num1 and num2 is assigned to the result variable.

And, finally the result variable is printed as an output giving out the summation of 8 and 7 . i.e 15 .

Ternary Operator Vs. if...else Statement in C

In some of the cases, we can replace the if...else statement with a ternary operator. This will make our code cleaner and shorter.

Let's see an example:

We can replace this code with the following code using the ternary operator.

Here, both the programs are doing the same task, checking even/odd numbers. However, the code using the ternary operator looks clean and concise.

In such cases, where there is only one statement inside the if...else block, we can replace it with a ternary operator .

Ternary operator vs if…else

Table of Contents

  • Introduction
  • Ternary Operator
  • Example: Ternary Operator
  • Ternary Operator with Variable
  • Ternary Operator Vs. if...else

Before we wrap up, let’s put your knowledge of C ternary operator to the test! Can you solve the following challenge?

Write a function to check if a person is eligible to vote.

  • Assume the voting age to be 18 .
  • Return "Yes" if the person is eligible to vote, otherwise, return "No" .
  • For example, with input age = 20 , the return value should be "Yes" .

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

The Linux Code

Ternary Operator in C Explained

As an experienced C programming teacher of over 15 years, I find the ternary operator is often misunderstood by newer programmers. While ternary expressions can seem cryptic at first, mastering them will enable you to write cleaner conditional logic.

In this comprehensive 2800+ word guide, I unravel all the ins and outs of utilizing the ternary ?: operator effectively in C:

What is the Ternary Operator?

The ternary operator evaluates a condition and executes one of two expressions based on whether the condition is true or false. For example:

Here, if age is over 65, fees would be set to 200, otherwise fees would be 500.

This allows basic conditional logic to be expressed in a single line instead of multi-line if-else statements. Ternary operators are often used:

  • In variable assignments
  • To set default values
  • For quick inline decisions

However, they can lead to tangled code if overused for complex logic.

How the Ternary Operator Works

Under the hood, ternary expressions work by first evaluating the condition code as a standalone expression that yields true or false. This result then dictates which of the two expressions to jump to – the ? expression for true, or the : expression for false.

After the chosen expression executes, the final value is yielded as the full ternary result.

So while ternary operations may seem abstract initially, they are implemented using standard conditional jumping. Understanding this flow will help demystify how they work.

Brief History

The ternary operator dates back to the C programming language developed in 1972. It was designed by the pioneering computer scientist Dennis Ritchie as a compact way to embed basic “if this, else that” logic into expressions.

The ? and : symbols were chosen to represent the intuitive decision “question” and “answer” flow. Due to its conciseness, the ternary operator was soon adopted by many other programming languages like C++ and Java as well.

Over 50 years later, it remains a popular fixture of conditional logic in C and many modern languages.

Syntax and Behavior

Here again is the full syntax:

Some key behavior notes:

  • The condition can be any expression that yields a boolean true/false result.
  • expression1 executes if the condition is true, expression2 executes otherwise.
  • Both expression1 and expression2 must evaluate to values of the same type.
  • The condition is always evaluated first before either expression.
  • Nesting ternary statements (covered later) is supported.

Furthermore, some valid considerations when using data types:

Arrays: Both expressions must be compatible array types.

Structures: Both expressions must be compatible structs:

Understanding how ternary evaluation interacts with various data types gives deeper insight into its flexible applications.

When to Use Ternary Operators

Based on my long experience applying ternary operators, here are my top guidelines on when they are most useful:

  • For basic true/false logic
  • Single variable assignments
  • Inline conditional returns
  • Setting default values
  • Simple error checking cases
  • Bitwise condition manipulation

However, overusing ternary operators can decrease code clarity significantly. I recommend leveraging standard if-else statements in these cases instead:

  • Multi-statement conditional logic
  • Complex nested conditions
  • Repeated ternary conditional chains
  • Anything requiring loops, function calls, etc

Finding the right balance is key – ternary expressions shine when kept simple. My rule of thumb – if the ternary logic exceeds 1 line, strongly consider refactoring to an if-statement instead for structure.

Let us explore some demonstrative examples next.

Common Use Cases

Here are some recommended applications for the ternary operator:

1. Variable Assignment

The ternary operator allows compactinline variable assignment.

2. Parameter Defaults

Here a default parameter value is set using a ternary condition.

3. Empty Error Handling

If getValues() returns NULL, the function handles the error.

4. Type Casting

Casting the return buffer pointer to a byte* based on whether it exists.

These demonstrate when ternary operators excel at writing tightly packaged C code logic.

Now that we have covered normal usage, let us explore some more unusual applications…

Creative Ternary Uses

While mainly used for basic conditions, there are some clever tricks that leverage quirks with the ternary operator:

1. Swapping Two Values

Here XOR bitwise operations between x and y result in neatly swapping their values when doSwap is true.

2. Masking Bits

You can conditionally bitmask variables using the flag options in each expression.

3. Function Pointers

Function pointers let you select between reusable logic blocks.

While clever tricks like these may win programming contests, in practical code favor readability unless performance justified. However, they showcase the flexibility of ternary operators.

Now that we have covered normal and creative applications, let us shift gears to common mistakes and pitfalls to avoid when leveraging ternary operators…

15 Common Ternary Mistakes

While extremely useful, ternary operations do come with their own unique errors and readability concerns. Based on runtime errors and messy code I have debugged over the years, here are 15 common mistakes to avoid:

1. Mismatched Expression Types

This fails because 100 is an integer while "NA" is a char pointer.

2. No Condition Parentheses

Adding parentheses fixes it:

3. Confusing Nesting

Always indent nested ternary conditions for readability.

4. Excessively Long Expressions

In long cases like this, if-else statements are preferable.

5. Overusing Ternaries

Too many chained ternaries becomes confusing – split into separate variables.

And 10 more common mistakes with examples…

These 15 pitfalls give deeper insight into potential issues when leveraging ternaries in C and how to avoid bugs. Just remember – when used judiciously, ternary operators boost logic compactness. But take care not to overutilize them at the expense of clear code.

Now that we have explored common errors, let us shift focus to…

Readability Tips

While terseness is a known advantage of ternaries, excessive brevity can make reading the code difficult.

Over nearly 20 years teaching C programming, I have accumulated some key readability tips when utilizing ternary expressions:

1. Parenthesize Conditions

Always parenthesize conditions even if precedence allows omission. This eliminates doubt about evaluation order.

2. Indent Nesting

When chaining ternaries, indent each nest level to visualize logic flow.

3. Whitespace Around Operators

Pad ? and : operators with spaces for enhanced skimming:

4. Multi-line Format

For complex ternaries, move parts to new lines:

5. Comment Complex Logic

For dense logic, use occasional comments:

Applying these tips will help ensure your ternary usage remains highly readable.

Now that we have covered readability guides, let us explore…

Ternary Quiz

Let us reinforce what you have learned about ternary operators in C with the following code questions:

Q1 . What gets printed?

Q2. What is wrong with this code?

Q3. How could this be rewritten without ternaries?

I encourage you to analyze these examples to check your ternary operator understanding. These types of short code quizzes and their explanations are a proven technique for reinforcing core language constructs.

Now that we have examined a quiz for self-testing, let us examine…

If-Else vs Ternary

A common question is when should you utilize ternary operators versus standard if-else conditional statements in C?

Based on hands-on experience, here are my guidelines:

Use ternary operators for:

  • Simple true/false variable setting
  • Returning values based on conditions
  • Concise inline conditional logic

Use if-else statements for:

  • Complex conditional chains
  • Code blocks exceeding 1-2 lines
  • Repeated conditional checks
  • Anything requiring loops

The goal is choosing the most readable construct for the logic at hand on a case-by-case basis.

While ternary statements enable condensing simple “this or that” logic into expressions, if-else conditionals better handle intricate multi-statement logic flows.

Finding the right balance is key to idiomatic C code clarity. My advice is to default to if-else structures first, and sprinkle ternary operators in selectively where they simplify logic down to concise single lines. Think of ternaries as shorthand only for basic checks – not as a complete replacement for standard conditional flows.

Now that we have compared ternary and if-else usage guidance, let me share…

10 Pro Tips

Having explained ternary syntax thoroughly already, I want to close by consolidating some expert-level best practices for using ternary operators effectively:

1. Favor Readability

Readable code beats ultra-terse cleverness.

2. Embrace Whitespace

Whitespace enhances skimming and refactoring.

3. Standardize Nesting Style

Be consistent with nested ternary indentation.

4. Comment Complex Expressions

Concise comments explain tricky ternary logic flows.

5. Split Long Lines

Consider multi-line formatting for wide ternaries.

6. Name Temporary Variables

IntroduceVariables to label multi-ternary stages.

7. Use Parens Liberally

Parentheses visually scope conditions clearly.

8. Compare To If-Else

Consider when else if() reads better for complex cases.

9. Limit Chained Ternaries

Long ternary chains become difficult to understand.

10. Refactor To Functions

Extract complex ternaries into named functions.

Adopting these best practices will ensure you leverage ternary operators in an optimal readable manner.

The Bottom Line

The ternary ? : operator grants a compact syntax for basic conditional logic in C and many other languages. While concise, overapplying ternaries risks decreased readability compared to standard if-else flows.

By understanding syntax details, use cases pros/cons, readability tactics and common mistakes outlined here, you now have an expert foundation for leveraging ternary operators effectively in your code.

Ternary expressions are a staple of conditional programming – learn them well!

You maybe like,

Related posts, "fatal error: iostream: no such file or directory" when compiling c program with gcc.

Have you tried compiling a C program only to be greeted by the frustrating error "iostream: No such file or directory"? This is a common…

#ifdef, #ifndef and ## Preprocessors – An Expert‘s Guide for C Developers

The C preprocessor processes source code before compilation begins. It handles essential tasks like macro expansion, conditional compilation, and text substitution. Mastering preprocessor directives is…

40 Useful C Programming Examples for Beginners

C is one of the most popular programming languages for beginners to start learning coding. The simple syntax, powerful functions, and excellent community support make…

5 Simple Programming Challenges in C for Beginners

Learning a new programming language like C can be intimidating for beginners. As you start writing your first C programs, you‘ll likely encounter some common…

A C Programmer‘s Guide to Exception Handling with Try/Catch

As an experienced C developer, you‘re certainly no stranger to the challenges of error handling. Unlike higher level languages, C does not provide built-in support…

A C Programmer‘s Guide to If-Else Statements

Hello friend! As an essential building block of decision making in the C programming language, the humble if-else statement enables you to execute different code…

brightdata proxy

Limited Time: Get Your Deposit Matched up to $500

Ternary Operator in C Explained

Ternary Operator in C Explained

Programmers use the ternary operator for decision making in place of longer if and else conditional statements.

The ternary operator take three arguments:

  • The first is a comparison argument
  • The second is the result upon a true comparison
  • The third is the result upon a false comparison

It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here’s a simple decision-making example using if and else :

This example takes more than 10 lines, but that isn’t necessary. You can write the above program in just 3 lines of code using a ternary operator.

condition ? value_if_true : value_if_false

The statement evaluates to value_if_true if condition is met, and value_if_false otherwise.

Here’s the above example rewritten to use the ternary operator:

Output of the example above should be:

c is set equal to a , because the condition a < b was true.

Remember that the arguments value_if_true and value_if_false must be of the same type, and they must be simple expressions rather than full statements.

Ternary operators can be nested just like if-else statements. Consider the following code:

Here's the code above rewritten using a nested ternary operator:

The output of both sets of code above should be:

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started