Skip to content
Justice Tech School

if, else if and else

Branch with conditions. C++17 allows an initialiser in if.

Example
#include <iostream>

int main() {
  int n = 15;
  if (n % 15 == 0) std::cout << "FizzBuzz\n";
  else if (n % 3 == 0) std::cout << "Fizz\n";
  else std::cout << n << "\n";
  if (int m = n * 2; m > 20) std::cout << m << "\n";
  return 0;
}

Result

FizzBuzz
30

Exercise

Else branch.

if (x) {}  {}

Quiz Test

What does if (init; cond) give?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.