c++conditional-operatorcomma-operator

Cannot understand comma expression


#include <iostream>
using namespace std;
int main()
{
    int a, b, c, max;
    cout<<"a="; cin>>a;
    cout<<"b="; cin>>b;
    cout<<"c="; cin>>c;
    a>b?(max=a, a=b, b=max):a;
    b>c?(max=b, b=c, c=max):a;
    a>b?(max=a, a=b, b=max):a;
    cout<<a<<"  "<<b<<"  "<<c;
}

This is a code where you can input 3 random numbers and it will put them in order. I don't understand this part, however:

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

How does it work, and why?

Let's say a = 6, b = 54, and c = 12.

  1. a>b?(max=a, a=b, b=max):a; <-- sets max to 6, then a to 54, then 54=max. then compares 6 to 54 which is false and writes a (6) as the first number?

  2. b>c?(max=b, b=c, c=max):a; <-- sets max to 54, b=12, 12=max. then compares 54 to 12 which is true in our case and writes c=12 as the second number?

  3. a>b?(max=a, a=b, b=max):a; <-- sets max to 6, a=54, 54=max. then compares 6 to 54 which is false and writes 6 again, wtf?

The program itself works correctly. I just don't understand how the algorithm works.


Solution

  • This:

    cond ? A : B
    

    is roughly equivalent to this:

    if (cond) {
        A;
    } else {
        B;
    }
    

    This:

    (X, Y, Z)
    

    is roughly equivalent to this:

    X;
    Y;
    Z;
    

    i.e. each expression is evaluated completely, in turn.

    Using these two rules, you should be able to trace the execution of your code. However, that code is grotesque, and should never have been written like that. So my recommendation is to just ignore it, and write the algorithm properly.