C++ Tutorial

C++ Ternary Operator

condition ? a : b picks one of two values without a full if.

One expression, two outcomes

The ternary operator is written condition ? a : b. C++ evaluates the condition. If it is true, the whole expression becomes a. If it is false, the expression becomes b. You get one value. You do not get a block of statements.

That is the difference from if. An if chooses which code runs. A ternary chooses whichvalue to use. Put it on the right of an assignment, inside cout, or as a return value.

Example

#include <iostream>
#include <string>
using namespace std;

int main() {
  int n = 8;
  string kind = (n % 2 == 0) ? "even" : "odd";
  cout << n << " is " << kind << endl;
  return 0;
}

Compile this in /cpp/try. Change n to 7 and run it again. The same line still picks a label; only the condition changed.

Same choice as a short if/else

This program is equivalent to an if with an else that each assign one string. The ternary version keeps the decision next to the variable. Use it when both arms are short and both produce the same kind of value.

Example

#include <iostream>
#include <string>
using namespace std;

int main() {
  int score = 72;
  string result = (score >= 50) ? "pass" : "fail";
  cout << result << endl;
  return 0;
}

Parentheses around the condition are not always required, but they make the test easy to see. This tutorial keeps them. The colon is not optional: every ? has a matching :.

Use it where a value is needed

Because the ternary is an expression, you can print it directly. You do not have to store it first. This program prints the larger of two integers. Swap the numbers and compile again.

Example

#include <iostream>
using namespace std;

int main() {
  int a = 9;
  int b = 14;
  cout << "larger: " << ((a > b) ? a : b) << endl;
  return 0;
}

Extra parentheses around the ternary keep cout from misreading the << chain. When the operator sits inside a larger expression, wrap it.

Both arms need a common type

a and b must make sense as one type. Two int values are fine. Twostring values are fine. Mixing "yes" with the integer 1 is not a value the compiler can pick cleanly. Match the arms.

ConditionIf trueIf false
n % 2 == 0"even""odd"
score >= 50"pass""fail"
a > bab

The condition itself is a boolean test: comparison, !, &&, ||. Do not write if inside the parentheses. The test is an expression, the same kind you already use in an if header.

Nesting is legal, not kind

You can put a ternary in an arm of another ternary. The compiler accepts it. A person reading the line has to count question marks. Prefer else if once you have three or more outcomes.

Example

#include <iostream>
#include <string>
using namespace std;

int main() {
  int score = 82;
  string grade = (score >= 90) ? "A" : (score >= 80) ? "B" : "C";
  cout << grade << endl;
  return 0;
}

This compiles. The if/else chain from the If Else chapter is easier to extend. Use a nested ternary only when both extra arms stay tiny.

It is not a block

Each arm is one expression. You cannot put two statements in an arm, and you should not hide acout plus an assignment in one ternary. If the true path needs two lines, write anif.

Do not use the operator for side effects such as incrementing in one arm and not the other. Readers expect a value, not a mutation. Keep the arms boring: literals, variables, or a short call that returns something.

When if is the better tool

Stay with if when you need braces, more than one statement, or a chain of ranges. Use the ternary when you are filling one variable or printing one chosen value. Next: nested loops, where one foris not enough to walk a table.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Physics

A current limit

A fuse or a software trip might allow 0.50 A. 0.47 A is within that. The ternary picks a word. For two outcomes it is readable. For three, use if/else.

Example

#include <iostream>
using namespace std;

int main() {
  double amps = 0.47;
  cout << (amps < 0.5 ? "within limit" : "trip") << endl;
  return 0;
}

Maths

The longer side

max(a, b) is the classic ternary. A 6 by 9 rectangle has longer edge 9. Geometry code uses this when a bounding box needs the larger extent.

max(a, b) = a > b ? a : b

Example

#include <iostream>
using namespace std;

int main() {
  double a = 6.0;
  double b = 9.0;
  double longer = a > b ? a : b;
  cout << "longer = " << longer << endl;
  return 0;
}

FAQ: C++ Ternary Operator

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ ternary operator examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ ternary operator in this C++ C++ lesson (C++ Ternary Operator).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.