samedi 26 juin 2021

C++ : Ambiguous Behavior of Ternary Operator

I tried and tested the following code to understand the behavior of ternary operator. But it is only making things complicated for me. The code:

#include<iostream>
using namespace std;

void print(bool a, bool b, bool c) {
    int x, y, z, w;
    cout << (a ? (b ? x = 5 + b : y = 10 + b) : (c ? z = 15 + c : w = 20 + c)) << endl;
    cout << x << " " << y << " " << z << " " << w << endl;
}

int main() {
    cout << "Hello world!\n";
    print(false, false, false);
    print(false, false, true);
    print(false, true, false);
    print(false, true, true);
    print(true, false, false);
    print(true, false, true);
    print(true, true, false);
    print(true, true, true);
    return 0;
}

And the output of this is as follows:

Hello world!
20
0 0 0 20
16
0 0 16 20
20
0 0 16 20
16
0 0 16 20
10
0 10 16 20
10
0 10 16 20
6
6 10 16 20
6
6 10 16 20

It doesn't look like this is following a procedure similar to the standard if-else procedure. Any guesses?

Aucun commentaire:

Enregistrer un commentaire