How to implement ternary operator in C++ without using conditional statements.
In the following condition : a ? b : c
If a is true, b will be executed.
Otherwise, c will be executed.
We can assume a, b and c as values.
We can code the equation as :
Result = (!!a)*b + (!a)*c
In above equation, is a is true, result will be b.
Otherwise, result will be c.
Asked In : Nvidia
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Conditional or Ternary Operator (?:) in C/C++
- Print "Even" or "Odd" without using conditional statement
- Set a variable without using Arithmetic, Relational or Conditional Operator
- Maximum of four numbers without using conditional or bitwise operator
- Programming puzzle (Assign value without any control statement)
- C/C++ Ternary Operator - Some Interesting Observations
- C++ | Nested Ternary Operator
- Conditionally assign a value without using conditional and arithmetic operators
- vector::operator= and vector::operator[ ] in C++ STL
- deque::operator= and deque::operator in C++ STL
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Operator Overloading '<<' and '>>' operator in a linked list class
- Print "Hello World" in C/C++ without using any header file
- Implementing Iterator pattern of a single Linked List
- Implementing own Hash Table with Open Addressing Linear Probing in C++
- Implementing Forward Iterator in BST
- Implementing upper_bound() and lower_bound() for Ordered Set in C++
- Interesting facts about switch statement in C
- Switch Statement in C/C++
- Break Statement in C/C++