Conditional Operator - PowerPoint PPT Presentation

1 / 6
About This Presentation
Title:

Conditional Operator

Description:

Only ternary operator in C / C . three operands. all other operators are unary or binary ... Structure of Statement Using Conditional Operator ... – PowerPoint PPT presentation

Number of Views:426
Avg rating:3.0/5.0
Slides: 7
Provided by: donaldl1
Category:

less

Transcript and Presenter's Notes

Title: Conditional Operator


1
Conditional Operator
  • A Shortcut for Certain Simple Decisions

2
Conditional Operator
  • Symbol is ?
  • Only ternary operator in C / C
  • three operands
  • all other operators are unary or binary
  • Provides a shortcut for a common programming
    situation

3
Common Situation
  • Traditional approach, using if statement
  • if (firstVal lt secondVal)
  • result firstVal
  • else
  • result secondVal
  • Alternative approach, using conditional operator
  • result (firstVal lt secondVal) ? firstVal
    secondVal

4
Structure of Statement Using Conditional Operator
  • result (firstVal lt secondVal) ? firstVal
    secondVal
  • test expression first
    second
  • expression expression
  • parentheses around test expression are optional
    but useful
  • commonly necessary to put parentheses around the
    whole conditional expression (depending on use
    and precedence)

5
Execution of a Statement that Uses the Conditonal
Operator
  • Evaluates the test expression
  • If true, statement takes on the value of the
    first expression
  • If false, statement takes on the value of the
    second expression
  • Note the entire conditional expression takes on
    the value of first expression or second
    expression
  • Conditional expression can be used anywhere that
    the value of the specified type can be used

6
Examples of Conditional Operator
  • Example 1
  • totPay hourlyRate ((hoursWorked lt 40) ?
  • hoursWorked hoursWorked 1.1)
  • Example 2
  • write out the numbers from 1 to 60 at five per
    line
  • for (int j 1 j lt 60 j)
  • cout ltlt setw(3) ltlt j ltlt ((j 5) ? " " "
    \n")
Write a Comment
User Comments (0)
About PowerShow.com