H'H
H'H

Reputation: 1678

Multiple conditional operator

I am familiar with Multiple conditions in ternary conditional operator like this:

( condition A ? value A :
  ( condition B ? value B : 
    ( condition C ? value C :
       ...
    )
  )
)

but I cannot understand how the code below works (function suppose to return an integer:

return (co1.Nr() < co2.Nr() ? -1 :
         ( co1.Nr() == co2.Nr() ? (co1.Id() < co2.Id() ? -1 : 
          (co1.Id() == co2.Id() ? 0 : 1)) : 1;

Will you please explain me?

Upvotes: 1

Views: 127

Answers (5)

Isaac Schneider
Isaac Schneider

Reputation: 172

Basically this is what the code does with if's statements

if (co1.Nr()< co2.Nr()){
        return -1;
    }else if (co1.Nr()==co2.Nr()){
        if (co1.Id() <co2.Id()){
            return -1;
        }else if( co1.Id() == co2.Id()){
            return 0;

        }else{
            return 1;
        }
    }else
    {
        return 1;
    }

Upvotes: 0

user3928919
user3928919

Reputation:

The condition map to following

if(co1.Nr() < co2.Nr())
    return -1;
else if(co1.Nr() == co2.Nr())
    if(co1.Id() < co2.Id())
        return -1;
    else if(co1.Id() == co2.Id())
        return 0;
    else
        return 1;
else
    return 1;

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Break it and understand. For ex: Consider the first part.

return (co1.Nr() < co2.Nr() ? -1 : (all_other_codes);

If the condition co1.Nr() < co2.Nr() true rerutn -1 else execute all_other_codes. Where as all_other_codes returns another integer.

Now look at all_other_codes

 ( co1.Nr() == co2.Nr() ? (co1.Id() < co2.Id() ? -1 : 
          (co1.Id() == co2.Id() ? 0 : 1)) : 1;

If co1.Nr() == co2.Nr() true return the value of

(co1.Id() < co2.Id() ? -1 : 
              (co1.Id() == co2.Id() ? 0 : 1))

else return 1.

Upvotes: 3

Ryan
Ryan

Reputation: 2084

if co1.Nr() < co2.Nr() return -1
else if co1.Nr() == co2.Nr() then
    if co1.Id() < co2.Id() return  -1 
    else if co1.Id() == co2.Id() return 0 
    else return 1
else return 1

Upvotes: 1

Paul Kienitz
Paul Kienitz

Reputation: 878

That's a primary and secondary sort: order by Nr, and if they're equal, order by Id. Returning -1, 0, and 1 is standard for comparison tests used for sorting.

Upvotes: 2

Related Questions