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 this article was helpful, share it .

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

ternary operator without assignment in c

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

ternary operator without assignment in c

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View PHP questions
  • View Python questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

How Do I Can Using Ternary Operator Without Return A Value?

ternary operator without assignment in c

3 solutions

  • Most Recent

ternary operator without assignment in c

Add your solution here

  • Read the question carefully.
  • Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  • If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Print

C Ternary Operator (With Examples)

C++ Course: Learn the Essentials

The C ternary operator, often represented as exp1 ? exp2 : exp3, is a valuable tool for making conditional decisions in C programming. This compact operator evaluates a condition and performs one of two expressions based on whether the condition is true or false. With its concise syntax and flexibility, the ternary operator is especially useful for streamlining conditional assignments.

The syntax of the Ternary Operator in C is:

Working of Syntax :

  • If the condition in the ternary operator is met (true), then the exp2 executes.
  • If the condition is false, then the exp3 executes.

Example of C Ternary Operator

The following example explains the working of Ternary Operator in C.

so, if the condition 10 > 15 is true (which is false in this case) mxNumber is initialized with the value 10 otherwise with 15 . As the condition is false so mxNumber will contain 15 . This is how Ternary Operator in C works.

NOTE: Ternary operator in C, like if-else statements, can be nested.

Assign the Ternary Operator to a Variable:

You can assign the result of the ternary operator to a variable, as shown in the previous example with the variable max. This is a common use case for the ternary operator, where the result of the condition is stored in a variable for later use.

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

The ternary operator and the if...else statement serve similar purposes but differ in syntax and use cases.

  • The C Ternary Operator is represented as exp1 ? exp2 : exp3 , providing a concise way to make conditional decisions.
  • If the condition exp1 is true, exp2 executes; otherwise, exp3 executes.
  • It's useful for simple conditional assignments and can improve code readability in such cases.
  • For more complex conditions, the if...else statement may be a better choice.
  • Understanding the ternary operator enhances your ability to write concise and expressive C code for conditional operations.

Ace your Coding Interview

  • DSA Problems
  • Binary Tree
  • Binary Search Tree
  • Dynamic Programming
  • Divide and Conquer
  • Linked List
  • Backtracking

Implement ternary operator without using conditional expressions

This post will implement a ternary-like operator in C without using conditional expressions like ternary operator, if–else expression, or switch-case statements.

The solution should implement the condition x ? a : b .

If x = 1 , a is returned; if x = 0 , b should be returned.

1. Develop custom expression

The idea is to use the expression x × a + !x × b or x × a + (1 - x) × b .

How this works?

Let’s consider the first expression x × a + !x × b :

  • For x = 1 , the expression reduces to (1 × a) + (!1 × b) = a .
  • For x = 0 , the expression reduces to (0 × a) + (!0 × b) = b .

The following C program demonstrates it:

Download    Run Code

Output: 20 10

2. Using Array

Another plausible way is to construct an array of size 2 in such a manner that index 0 of the array holds the value of b and index 1 holds the value of a , as shown below:

int arr[] = { b, a };

Then we can return the value present at index 0 or 1 depending upon the value of x .

  • For x = 1 , the expression arr[x] reduces to arr[1] = a .
  • For x = 0 , the expression arr[x] reduces to arr[0] = b .

This is demonstrated below in C. Please note that this approach doesn’t use any operators in C, such as arithmetic, relational, logical, conditional, etc.

3. Using Short Circuiting

Another approach is to use short-circuiting in boolean expressions. For AND operations in C such as x && y , y is evaluated only if x is true. Similarly, for OR operation like x || y , y is only evaluated if x is false. We can apply this logic to solve this problem. Consider the following code snippet:

x && ((result = a) || !a) || (result = b)

Initially, we check whether x is 1 or 0. If x = 1 , the result is set to a and result = b subexpression won’t get executed. If x = 0 , the (result = a) || !a subexpression won’t be executed and the result is set to b . Please note that !a is added to handle the case when a = 0 .

  This approach is demonstrated below in C:

Find minimum number without using conditional statement or ternary operator
Find maximum number without using conditional statement or ternary operator
Check if a number is even or odd without using any conditional statement

Rate this post

Average rating 4.06 /5. Vote count: 62

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and support our growth. Happy coding :)

guest

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

?: operator - the ternary conditional operator

  • 11 contributors

The conditional operator ?: , also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false , as the following example shows:

As the preceding example shows, the syntax for the conditional operator is as follows:

The condition expression must evaluate to true or false . If condition evaluates to true , the consequent expression is evaluated, and its result becomes the result of the operation. If condition evaluates to false , the alternative expression is evaluated, and its result becomes the result of the operation. Only consequent or alternative is evaluated. Conditional expressions are target-typed. That is, if a target type of a conditional expression is known, the types of consequent and alternative must be implicitly convertible to the target type, as the following example shows:

If a target type of a conditional expression is unknown (for example, when you use the var keyword) or the type of consequent and alternative must be the same or there must be an implicit conversion from one type to the other:

The conditional operator is right-associative, that is, an expression of the form

is evaluated as

You can use the following mnemonic device to remember how the conditional operator is evaluated:

Conditional ref expression

A conditional ref expression conditionally returns a variable reference, as the following example shows:

You can ref assign the result of a conditional ref expression, use it as a reference return or pass it as a ref , out , in , or ref readonly method parameter . You can also assign to the result of a conditional ref expression, as the preceding example shows.

The syntax for a conditional ref expression is as follows:

Like the conditional operator, a conditional ref expression evaluates only one of the two expressions: either consequent or alternative .

In a conditional ref expression, the type of consequent and alternative must be the same. Conditional ref expressions aren't target-typed.

Conditional operator and an if statement

Use of the conditional operator instead of an if statement might result in more concise code in cases when you need conditionally to compute a value. The following example demonstrates two ways to classify an integer as negative or nonnegative:

Operator overloadability

A user-defined type can't overload the conditional operator.

C# language specification

For more information, see the Conditional operator section of the C# language specification .

Specifications for newer features are:

  • Target-typed conditional expression
  • Simplify conditional expression (style rule IDE0075)
  • C# reference
  • C# operators and expressions
  • if statement
  • ?. and ?[] operators
  • ?? and ??= operators
  • ref keyword

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Dot Net Tutorials

Unary vs Binary vs Ternary Operators in C

Back to: C Tutorials For Beginners and Professionals

Unary vs. Binary vs. Ternary Operators in C

In this article, I will discuss Unary vs. Binary vs. Ternary Operators in C with Examples. Please read our previous article discussing Unary Operators in C Language. In C programming, operators are symbols that tell the compiler to perform specific mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They can be categorized into unary, binary, and ternary operators based on the number of operands they take.

Unary Operators in C

Unary operators in C are operators that operate on a single operand. They are used to perform various operations, such as incrementing/decrementing a value, negating an expression, or dereferencing a pointer. Here are the most commonly used unary operators in C:

Increment (++): Increases the value of its operand by 1. It can be used in two forms:

  • Prefix (++x): Increments the value of x and then returns the new value.
  • Postfix (x++): Returns the value of x and then increments it.

Decrement (–): Decreases the value of its operand by 1. Similar to increment, it also has two forms:

  • Prefix (–x): Decrements the value of x and then returns the new value.
  • Postfix (x–): Returns the value of x and then decrements it.

Unary Minus (-): Negates the value of its operand.

Logical NOT (!): Inverts the boolean value of its operand. If the operand is non-zero, it returns 0 (false), and if the operand is zero, it returns 1 (true).

Bitwise NOT (~): Performs a bitwise negation on its operand, inverting each bit.

Address-of (&): Returns the memory address of its operand.

Dereference (*): Accesses the value at the address pointed to by its operand (the opposite of the address-of operator).

Sizeof: Returns the size of a data type or an object in bytes.

These unary operators are widely used in C programming for various purposes, including memory management, arithmetic operations, and logical operations.

Binary Operators in C

In the C programming language, binary operators are used to perform operations on two operands. Here are the most commonly used binary operators in C:

Arithmetic Operators:

  • Addition (+): Adds two operands. E.g., a + b.
  • Subtraction (-): Subtracts the second operand from the first. E.g., a – b.
  • Multiplication (*): Multiplies two operands. E.g., a * b.
  • Division (/): Divides the numerator by the denominator. E.g., a / b.
  • Modulus (%): Returns the remainder of a division. E.g., a % b.

Relational Operators:

  • Equal to (==): Checks if two operands are equal. Returns true if they are. E.g., a == b.
  • Not equal to (!=): Checks if two operands are not equal. E.g., a != b.
  • Greater than (>): Checks if the left operand is greater than the right operand. E.g., a > b.
  • Less than (<): Checks if the left operand is less than the right operand. E.g., a < b.
  • Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right operand. E.g., a >= b.
  • Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand. E.g., a <= b.

Logical Operators:

  • Logical AND (&&): Returns true if both operands are true. E.g., a && b.
  • Logical OR (||): Returns true if either of the operands is true. E.g., a || b.
  • Logical NOT (!): Used to reverse the logical state of its operand. E.g., !a.

Bitwise Operators:

  • Bitwise AND (&): Performs a bitwise AND on two integers. E.g., a & b.
  • Bitwise OR (|): Performs a bitwise OR on two integers. E.g., a | b.
  • Bitwise XOR (^): Performs a bitwise exclusive OR on two integers. E.g., a ^ b.
  • Bitwise left shift (<<): Shifts the bits of the first operand to the left by the number of positions specified by the second operand. E.g., a << 2.
  • Bitwise right shift (>>): Shifts the bits of the first operand to the right by the number of positions specified by the second operand. E.g., a >> 2.

Assignment Operators:

  • Simple assignment (=): Assigns the value of the right operand to the left operand. E.g., a = b.
  • Add and assign (+=): Adds the right operand to the left operand and assigns the result to the left operand. E.g., a += b.
  • Subtract and assign (-=): Subtracts the right operand from the left operand and assigns the result to the left operand. E.g., a -= b.
  • Multiply and assign (*=): Multiply the right operand with the left operand and assign the result to the left operand. E.g., a *= b.
  • Divide and assign (/=): Divides the left operand by the right operand and assigns the result to the left operand. E.g., a /= b.
  • Modulus and assign (%=): Applies modulus operation and assigns the result to the left operand. E.g., a %= b.

These binary operators are fundamental to performing calculations, making comparisons, and manipulating data at the bit level in C programming.

Ternary Operators in C

Ternary operators in C are a shorthand way of writing conditional statements. They are a compact form of the if-else statement and are often used for simple conditional assignments. The syntax of the ternary operator in C is:

condition ? expression1 : expression2;

Here’s how it works:

  • condition is an expression that evaluates to true or false.
  • expression1 is the value or statement that is executed if the condition is true.
  • expression2 is the value or statement that is executed if the condition is false.

For example:

In this example, the ternary operator checks if a is greater than b. If true, max is assigned the value of a; otherwise, it is assigned the value of b.

In the next article, I am going to discuss Variables in C Programming Language with Examples. Here, in this article, I explain Unary vs Binary vs Ternary Operators in C Language with examples. I hope you enjoy this Unary vs Binary vs Ternary Operators in C Language article. Please give your feedback and suggestions about this article.

dotnettutorials 1280x720

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Compiler tricks in x86 assembly: Ternary operator optimization

One relatively common compiler optimization that can be handy to quickly recognize relates to conditional assignment (where a variable is conditionally assigned either one value or an alternate value). This optimization typically happens when the ternary operator in C (“?:”) is used, although it can also be used in code like so:

The primary optimization that the compiler would try to make here is the elimination of explicit branch instructions.

Although conditional move operations were added to the x86 instruction set around the time of the Pentium II, the Microsoft C compiler still does not use them by default when targeting x86 platforms (in contrast, x64 compiler uses them extensively). However, there are still some tricks that the compiler has at its disposal to perform such conditional assignments without branch instructions.

This is possible through clever use of the “conditional set ( setcc )” family of instructions (e.g. setz ), which store either a zero or a one into a register without requiring a branch. For example, here’s an example that I came across recently:

Broken up into the individual relevant steps, this code is something along the lines of the following in pseudo-code:

The key trick here is the use of a setcc instruction, followed by a dec instruction and an and instruction. If one takes a minute to look at the code, the meaning of these three instructions in sequence becomes apparent. Specifically, a setcc followed by a dec sets a register to either 0 or 0xFFFFFFFF (-1) based on a particular condition flag. Following which the register is ANDed with a constant, which depending on whether the register is 0 or -1 will result in the register being set to the constant or being left at zero (since anything AND zero is zero, while ANDing any particular value with 0xFFFFFFFF yields the input value). After this sequence, a second constant is summed with the current value of the register, yielding the desired result of the operation.

(The initial constant is chosen such that adding the second constant to it results in one of the values of the conditional assignment, where the second constant is the other possible value in the conditional assignment.)

Cleaned up a bit, this code might look more like so:

This sort of trick is also often used where something is conditionally set to either zero or some other value, in which case the “add” trick can be omitted and the non-zero conditonal assignment value is used in the AND step.

A similar construct with the sbb instruction and the carry flag can also be constructed (as opposed to setcc , if sbb is more convenient for the particular case at hand). For example, the sbb approach tends to be preferred by the compiler when setting a value to zero or -1 as a further optimization on this theme as it avoids the need to decrement, assuming that the input value was already zero initially and the condition is specified via the carry flag.

This entry was posted on Thursday, October 18th, 2007 at 10:14 am and is filed under Reverse Engineering . You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

4 Responses to “Compiler tricks in x86 assembly: Ternary operator optimization”

[…] Nynaeve Adventures in Windows debugging and reverse engineering. « Compiler tricks in x86 assembly: Ternary operator optimization […]

This is excellent, thank you! I’ve just used this in a program I’m writing which has to do runtime code generation (pretty complex virtual function hooking for protoypes that are unknown at compile time)..

“Although conditional move operations were added to the x86 instruction set around the time of the Pentium II,” Actually Pentium Pro.

Funny, the first time I saw one jump bounds check in ZX Spectrum ROM. This looks similar.

Nynaeve is proudly powered by WordPress Entries (RSS) and Comments (RSS) .

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Conditional (ternary) operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy . This operator is frequently used as an alternative to an if...else statement.

An expression whose value is used as a condition.

An expression which is executed if the condition evaluates to a truthy value (one which equals or can be converted to true ).

An expression which is executed if the condition is falsy (that is, has a value which can be converted to false ).

Description

Besides false , possible falsy expressions are: null , NaN , 0 , the empty string ( "" ), and undefined . If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse .

A simple example

Handling null values.

One common usage is to handle a value that may be null :

Conditional chains

The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:

This is equivalent to the following if...else chain.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Nullish coalescing operator ( ?? )
  • Optional chaining ( ?. )
  • Making decisions in your code — conditionals
  • Expressions and operators guide

Learn C++ practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c++ interactively, c++ introduction.

  • C++ Variables and Literals
  • C++ Data Types
  • C++ Basic I/O
  • C++ Type Conversion

C++ Operators

  • C++ Comments

C++ Flow Control

  • C++ if...else
  • C++ for Loop
  • C++ do...while Loop
  • C++ continue
  • C++ switch Statement
  • C++ goto Statement
  • C++ Functions
  • C++ Function Types
  • C++ Function Overloading
  • C++ Default Argument
  • C++ Storage Class
  • C++ Recursion
  • C++ Return Reference

C++ Arrays & String

  • Multidimensional Arrays
  • C++ Function and Array
  • C++ Structures
  • Structure and Function
  • C++ Pointers to Structure
  • C++ Enumeration

C++ Object & Class

  • C++ Objects and Class
  • C++ Constructors
  • C++ Objects & Function

C++ Operator Overloading

  • C++ Pointers
  • C++ Pointers and Arrays
  • C++ Pointers and Functions
  • C++ Memory Management
  • C++ Inheritance
  • Inheritance Access Control
  • C++ Function Overriding
  • Inheritance Types
  • C++ Friend Function
  • C++ Virtual Function
  • C++ Templates

C++ Tutorials

  • Check Whether Number is Even or Odd

C++ if, if...else and Nested if...else

  • Add Complex Numbers by Passing Structure to a Function
  • Subtract Complex Number Using Operator Overloading
  • C++ Ternary Operator

In C++, the ternary operator (also known as the conditional operator ) can be used to replace if...else in certain scenarios.

Ternary Operator in C++

A ternary operator evaluates the test condition and executes a block of code based on the result of the condition.

Its syntax is

Here, condition is evaluated and

  • if condition is true , expression1 is executed.
  • And, if condition is false , expression2 is executed.

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

Example : C++ Ternary Operator

Suppose the user enters 80 . Then, the condition marks >= 40 evaluates to true . Hence, the first expression "passed" is assigned to result .

Now, suppose the user enters 39.5 . Then, the condition marks >= 40 evaluates to false . Hence, the second expression "failed" is assigned to result .

  • When to use a Ternary Operator?

In C++, the ternary operator can be used to replace certain types of if...else statements.

For example, we can replace this code

Here, both programs give the same output. However, the use of the ternary operator makes our code more readable and clean.

Note: We should only use the ternary operator if the resulting statement is short.

  • Nested Ternary Operators

It is also possible to use one ternary operator inside another ternary operator. It is called the nested ternary operator in C++.

Here's a program to find whether a number is positive, negative, or zero using the nested ternary operator.

In the above example, notice the use of ternary operators,

  • (number == 0) is the first test condition that checks if number is 0 or not. If it is, then it assigns the string value "Zero"  to result .
  • Else, the second test condition (number > 0) is evaluated if the first condition is false .

Note : It is not recommended to use nested ternary operators. This is because it makes our code more complex.

Table of Contents

  • Example :Ternary Operator

Sorry about that.

Related Tutorials

C++ Tutorial

C++ Operator Precedence and Associativity

C Data Types

C operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

Related Articles

  • Solve Coding Problems
  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C
  • Const Qualifier in C
  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Relational Operators in C
  • Bitwise Operators in C
  • C Logical Operators

Assignment Operators in C

  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

  • C Structures
  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C Preprocessor Directives
  • How a Preprocessor works in C?
  • Header Files in C
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C
  • _Generics Keyword in C
  • Multithreading in C
  • C Programming Interview Questions (2024)
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

ternary operator without assignment in c

Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y';

2. “+=” : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example: (a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11.

3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left. Example: (a -= b) can be written as (a = a - b) If initially value stored in a is 8. Then (a -= 6) = 2.

4. “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example: (a *= b) can be written as (a = a * b) If initially value stored in a is 5. Then (a *= 6) = 30.

5. “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example: (a /= b) can be written as (a = a / b) If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

Please Login to comment...

  • C-Operators
  • cpp-operator
  • manshisharma13

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Ternary Operator

    ternary operator without assignment in c

  2. Conditional or Ternary Operator (?:) in C

    ternary operator without assignment in c

  3. Ternary Operator Example In C

    ternary operator without assignment in c

  4. Ternary Operator (? :) in C# with Examples

    ternary operator without assignment in c

  5. C Programming Tutorial

    ternary operator without assignment in c

  6. Opérateur conditionnel ou ternaire (?:) en C/C++

    ternary operator without assignment in c

VIDEO

  1. Supply through E Commerce Operator without taking GST Registration

  2. USE OF TERNARY OPERATOR IN C PROGRAMMING

  3. Smooth operator without the music

  4. Operators in C language

  5. Ternary / Conditional Operator

  6. Ternary Operator & If, else if Condition in JavaScript

COMMENTS

  1. c

    Using a ternary operator without assigning it to a variable Ask Question Asked 8 years, 4 months ago Modified 8 years, 4 months ago Viewed 634 times 1 I know this is possible, but is it good practice to use a ternary operator to call functions rather than using an if statement? if (x) { a (); } else if (y) { b (); } else if (z) { c (); }

  2. C Ternary Operator (With Examples)

    In C programming, we can also assign the expression of the ternary operator to a variable. For example, variable = condition ? expression1 : expression2; Here, if the test condition is true, expression1 will be assigned to the variable. Otherwise, expression2 will be assigned.

  3. Conditional or Ternary Operator (?:) in C

    The conditional operator in C is kind of similar to the if-else statement as it follows the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible. It is also known as the ternary operator in C as it operates on three operands.

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

  5. How Do I Can Using Ternary Operator Without Return A Value?

    Keep in mind that .NET Collections Remove<T> operator returns a boolean value indicating the success or failure of a removal; you can use that return value, or ignore it. If you need to keep track of whether the removal was successful, try this: C#. bool itemIsRemoved = myCollection.Remove (myCollection.FirstOrDefault (p => p != null ));

  6. C Ternary Operator (With Examples)

    NOTE: Ternary operator in C, like if-else statements, can be nested. Assign the Ternary Operator to a Variable: You can assign the result of the ternary operator to a variable, as shown in the previous example with the variable max. This is a common use case for the ternary operator, where the result of the condition is stored in a variable for ...

  7. Implement ternary operator without using conditional expressions

    int arr [] = { b, a }; Then we can return the value present at index 0 or 1 depending upon the value of x. For x = 1, the expression arr [x] reduces to arr [1] = a. For x = 0, the expression arr [x] reduces to arr [0] = b. This is demonstrated below in C. Please note that this approach doesn't use any operators in C, such as arithmetic ...

  8. Ternary conditional operator

    ternary conditional operator ternary operator that is part of the syntax for basic conditional expressions programming languages. It is commonly referred to as the (abbreviated ). An expression a ? b : c if the value of is true, and otherwise to . One can read it aloud as "if a then b otherwise c".

  9. javascript

    12 Edit This isn't a question of whether or not the ternary operator is harmful. It's about whether or not there's a consensus about whether or not it should be used outside of assignment statements. /Edit Based on a boolean, I want to call one of two different functions (with no return value). I wrote this bit of javascript:

  10. ?: operator

    The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false, as the following example shows: C# string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ? "Cold."

  11. Unary vs Binary vs Ternary Operators in C

    Here are the most commonly used unary operators in C: Increment (++): Increases the value of its operand by 1. It can be used in two forms: Prefix (++x): Increments the value of x and then returns the new value. Postfix (x++): Returns the value of x and then increments it. Decrement (-): Decreases the value of its operand by 1.

  12. Compiler tricks in x86 assembly: Ternary operator optimization

    Compiler tricks in x86 assembly: Ternary operator optimization. One relatively common compiler optimization that can be handy to quickly recognize relates to conditional assignment (where a variable is conditionally assigned either one value or an alternate value). This optimization typically happens when the ternary operator in C ("?:") is ...

  13. Implementing ternary operator without any conditional statement

    1. Using Binary Operator We can code the equation as : Result = (!!a)*b + (!a)*c In above equation, if a is true, the result will be b. Otherwise, the result will be c. C++ Python 3 PHP Javascript #include <bits/stdc++.h> int ternaryOperator (int a, int b, int c) { return ( (!!a) * b + (!a) * c); } int main () { int a = 1, b = 10, c = 20;

  14. Conditional (ternary) operator

    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (? ), then an expression to execute if the condition is truthy followed by a colon (: ), and finally the expression to execute if the condition is falsy .

  15. C++ Ternary Operator (With Examples)

    In C++, the ternary operator (also known as the conditional operator) can be used to replace if...else in certain scenarios. Ternary Operator in C++ A ternary operator evaluates the test condition and executes a block of code based on the result of the condition. Its syntax is condition ? expression1 : expression2; Here, condition is evaluated and

  16. C++ Ternary or Conditional Operator

    Courses Practice In C++, the ternary or conditional operator ( ? : ) is the shortest form of writing conditional statements. It can be used as an inline conditional statement in place of if-else to execute some conditional code. Syntax of Ternary Operator ( ? : ) The syntax of the ternary (or conditional) operator is:

  17. Java Ternary without Assignment

    30 Nope you cannot do that. The spec says so. The conditional operator has three operand expressions. ? appears between the first and second expressions, and : appears between the second and third expressions. The first expression must be of type boolean or Boolean, or a compile-time error occurs.

  18. c++

    Ternary conditional and assignment operator precedence Ask Question Asked 12 years, 4 months ago Modified 8 months ago Viewed 9k times 35 I'm confused about direct assignment and ternary conditional operators precedence:

  19. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators.