Ruirui
Ruirui

Reputation: 141

Why is the ternary operator returning 0?

Why does the following code have '0' as output?

#include <bits/stdc++.h>

int main() {
    int max = 5;
    std::cout << (false) ? "impossible" : std::to_string(max);
}

Upvotes: 0

Views: 206

Answers (1)

Thomas Sablik
Thomas Sablik

Reputation: 16448

The statement

std::cout << false ? "impossible" : std::to_string(max);

is equivalent to

(std::cout << false) ? "impossible" : std::to_string(max);

because << has higher precedence than ?: and false is printed as 0.

You probably expected this

std::cout << (false ? "impossible" : std::to_string(max));

You should read operator precedence to avoid such surprises.

Upvotes: 5

Related Questions