Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 566
erasmus77 Avatar asked Sep 04 '26 13:09

erasmus77


1 Answers

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.

like image 115
Oliver Charlesworth Avatar answered Sep 07 '26 08:09

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!