livelive96
livelive96

Reputation: 43

Are both of these statements equivalent?

statement 1

return (x1 > x2) ? ((x1 > x3) ? x1: x3): ((x2 > x3) ? x2: x3);

statement 2

if(x1>x2){
    if(x1>x3){
        return x1;
    }
    else{
        return x3;
    }
}
else if(x2>x3){
    return x2;
}
else return x3;

Upvotes: 2

Views: 78

Answers (3)

chux
chux

Reputation: 153447

Are both of these statements equivalent?

With variant types: possibly no.

Example: The a ? b : c causes b and c to covert to a common type, yet not so with if then else.

#include<stdio.h>

double foo(int x1, float x2, int x3) {
  // Inexact conversions to float      vv                      vv
  return (x1 > x2) ? ((x1 > x3) ? x1 : x3) : ((x2 > x3) ? x2 : x3);
}

double bar(int x1, float x2, int x3) {
  if (x1 > x2) {
    if (x1 > x3) {
      return x1;
    } else {
      return x3;
    }
  } else if (x2 > x3) {
    return x2;
  } else
    return x3;
}

int main(void) {
  printf("%f\n", foo(INT_MAX, 1.0f, 0));
  printf("%f\n", bar(INT_MAX, 1.0f, 0));
}

Output

2147483648.000000
2147483647.000000

Or possibly a compiler error under both approaches.

double foo2(int x1, float x2, int *x3) {
  // error: invalid operands to binary > (have 'float' and 'int *')
  return (x1 > x2) ? ((x1 > x3) ? x1 : x3) : ((x2 > x3) ? x2 : x3);
}

Upvotes: 3

dbush
dbush

Reputation: 223739

Yes, they are equivalent.

Starting with the inner if:

if(x1>x3){
    return x1;
}
else{
    return x3;
}

This is the same as:

return (x1 > x3) ? x1 : x3;

Let's call the above expression X:

Now looking at the outer if / else if /else:

if(x1>x2){
    return X;
}
else if(x2>x3){
    return x2;
}
else return x3;

This becomes:

return (x1>x2) ? X : ((x2>x3) ? x2 : x3);

Substituting in X:

return (x1 > x2) ? ((x1 > x3)? x1 :x3) : ((x2 > x3) ? x2 : x3);

This can be a bit more clear if you split this up over multiple lines:

return (x1 > x2) ? ((x1 > x3)? 
                       x1 :
                       x3) : 
       (x2 > x3) ? x2 : x3;

If the there were only one level of if statements I might go with the ternary operator, but because the levels are nested I would stick with the more explicit set of statements for clarity.

Upvotes: 1

paddy
paddy

Reputation: 63471

Yes, they are equivalent, provided the types of x1, x2 and x3 are all the same. If types are different but convertible to the return type, then statement 1 will result in a compilation error.

Upvotes: 3

Related Questions