hqt
hqt

Reputation: 30284

Change from if else to ternary operator

Here is the normal code :

       if(a==b)
            printf("equal");
        else if(a>b)
            printf("bigger");
        else
            printf("smaller");

My teacher want to change if/else to this structure:

printf("%s",a>b?"bigger":"smaller")

of course, this just a simple and standard. and I don't know how to apply this to above code to replace if/else.

Upvotes: 0

Views: 1563

Answers (4)

Josh Petitt
Josh Petitt

Reputation: 9589

Some like the ternary operator, some do not.

You teacher is good for showing you it, and letting you apply it. Like anything, it can be abused.

However, there is one really cool use of it that cannot be done any other way (AFAIK). Consider the following:

#define MAX(_a_, _b_) (((_a_) > (_b_)) ? (_a_) : (_b_))

Notice you can use this like this:

int x = MAX(5, 17);

I don't know of any way you could do this with an if...else statement. (You could do it with a function call, but that isn't the point.)

Personally, I avoid ternary in all but the simplest of cases.

And for the record, 1 line code in C does not necessarily execute any faster than 4 line code. Be wary of using ternary just so you can write 1 liners.

https://softwareengineering.stackexchange.com/questions/28314/is-the-ternary-operator-evil Ternary operator: bad or good practice?

Upvotes: 1

zellio
zellio

Reputation: 32524

Your teacher is telling you to use the ternary operator.

// Generally it looks like this 
( predicate ) ? If_True : If_False ;

the operator can be stacked with it self, ( using parenthetical statements ) to generate more complex logic.

( predicate_0 ) ? If_True : ( ( predicate_1 ) ? If_True : ... )) ;

Though generally stacking the ternary operator in this fashion makes for code a bit harder to read. and in most cases you are better off using the if ... else block

Upvotes: 5

dreamerkumar
dreamerkumar

Reputation: 1550

printf("%s", a == b? "equal" : (a > b? "bigger" : "smaller"));

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838964

It's not generally a good idea to use nested conditional operators, but it can be done:

printf("%s", a==b ? "equal" : (a > b ? "bigger" : "smaller"));

Upvotes: 9

Related Questions