Replacing the conditional operator by a function
Question
A student argues that for integers, c ? a : b could be replaced by an ordinary function choose(c, a, b) with no change in behaviour. Is that right?
Short answer
No. A function evaluates all its arguments before the call, whereas the conditional operator evaluates only the selected branch. So side effects, expensive computations or invalid expressions in the unchosen branch (e.g. p ? *p : 0) behave differently. The operator can also yield an lvalue and works for any type without overloading.
Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.23, p.227; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solutionLessons behind this question
- Conditional Probability, Total Probability, and Bayes' Rule
- Worked Examples — Probability Trees, Monty Hall, and Bayesian Updating
- Algorithms, Growth Rates, and Asymptotic Notation
Start with a free lesson: Probability Fundamentals is part of a free topic. Create a free account, no card needed, to read it in full with worked solutions.
Read it free