How to Use the ?: Decision-Making Function in C Programming - dummies

How to Use the ?: Decision-Making Function in C Programming

By Dan Gookin

Perhaps the most cryptic of the decision-making tools in C, ?: is a favorite of programmers who enjoy obfuscating their code. It generates results based on if-true and if-false statements.


#include <stdio.h>
int main()
  int a,b,larger;
  printf("Enter value A: ");
  printf("Enter different value B: ");
  larger = (a > b) ? a : b;
  printf("Value %d is larger.n",larger);

Specifically, you want to look at Line 12:

larger = (a > b) ? a : b;

Exercise 1: Create a project using the source code from And Then It Gets Weird. Build and run just to prove that the weirdo ?: thing works.

Officially, ?: is known as a ternary operator: It’s composed of three parts. It’s a comparison and then two parts: value-if-true and value-if-false. Written in plain, hacker English, the statement looks like this:

result = comparison ? if_true : if_false;

The statement begins with a comparison. Any comparison from an if statement works, as do all operators, mathematical and logical. You can enclose the comparison in parentheses, though that’s not a requirement.

When comparison is true, the if_true portion of the statement is evaluated and that value stored in the result variable. Otherwise, the if_false solution is stored.

Exercise 2: Rewrite the source code form And Then It Gets Weird using an if-else structure to carry out the decision and result from the ?: ternary operator in Line 12.