
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
What does '?' do in C/C++?
The operator ‘?’ is known as ternary operator as it requires three operands to act upon. It can be represented by “ ? : ”. It is also known as conditional operator. The operator improves the performance and reduces the lines of code.
Here is the syntax of ternary operator in C language,
Expression1 ? Expression2 : Expression3
Here is an example of Ternary Operator in C language,
Example
#include <stdio.h> int main() { int a = -1; double b = 26.4231; int c = a? printf("True value : %lf",b):printf("False value : 0"); return 0; }
Output
Here is the output
True value : 26.423100
Expression1 will evaluate always while expression2 & expression3 are dependent on the outcome of expression1. If the outcome of expression1 is non-zero or negative, expression2 will display, otherwise expression3 will display.
The ternary operator has a return type. The return type depends on expression2 and also on the convertibility of expression3 to expression2. If they are not convertible, the compiler will throw an error.
Here is another example of ternary operator in C language,
Example
#include <stdio.h> int main() { int x = -1, y = 3; double b = x+y+0.5; int c = x<y? printf("True value : %lf",b):printf("False value : 0"); return 0; }
Output
Here is the output
True value : 2.500000
- Related Articles
- What does an auto keyword do in C++?
- What does the keyword var do in C#?
- What does the interface ICollection do in C#
- What does the interface IEnumerable do in C#?
- What does the interface IList do in C#?
- What does the interface ICloneable do in C#?
- What does the interface IStructuralComparable do in C#?
- What does the interface IStructuralEquatable do in C#?
- What does the method addAll(Coll C)do in java?
- What does Array.Rank property of array class do in C#?
- What does the @ prefix do on string literals in C#?
- What does Array.IsFixedSize property of array class do in C# ?
- What does Array.IsReadOnly property of array class do in C#?
- What does Array.Length property of array class do in C#?
- What does Array.LongLength property of array class do in C#?
