Comma and conditional operators

Comma operator

The comma operator (,) allows you to view multiple expressions where only one sentence is permitted. The comma operator checks the left operator, then the right operator, and returns the result of the correct operand.

For example:

# include <iostream> int main () { int x {1}; int {0}; std :: cout << (++ x, ++ y); // increment x and y, checks to the correct operator return 0; }

First, the left-hand operator is tested, magnifying x from 1 to 2. Next, the right-hand operator is tested, which rises by 2 to 3. printed later in the console.

Conditional Operator

Conditional operator (? Because historically, it was only a C ++ ternary operator, it is sometimes referred to as a "ternary operator."

The ?: operator provides a shorthand method for doing a particular type of if/else statement. Would you please review lesson 4.10 -- Introduction to if statements if you need a brush up on if/else before proceeding?

The if / else statement takes the following form:

if (status)
  • If the condition proves to be true, a statement1 is made. Otherwise, statement2 is made.


variable = Expression1 ? Expression2 : Expression3

If the condition checks to be valid, then expression1 is performed. Otherwise, expression2 is performed. Note that expression2 is not an option.

Consider an if / else statement that looks like this:


#include <iostream> using namespace std; int main() { int m = -5, n = 4; (m > n) ? cout<<"TRUE: ":cout<<"FALSE"; return 0; }


string type