Reputation: 12431
I'm a newbie to C, I understand why ternary operators can be useful, less code than if/else blocks.
I have been given some C code to maintain, and one thing I've noticed is the previous programmer used ternary operators like this
myInt = (!myInt) ? MACRO1 : MACRO2;
Does this accomplish exactly the same thing as this:
myInt = myInt ? MACRO2 : MACRO1;
Is this just a style thing? Perhaps it makes sense to think "if not" myInt, instead of "if"?
Upvotes: 2
Views: 200
Reputation: 124790
Yes, you are correct. It seems as though the originator of that code wanted to make the expression slightly more confusing than it needed to be.
Upvotes: 2
Reputation: 1347
I prefer the second example as it is not using reverse logic, therefore easier to understand and less clutter.
myInt = myInt ? MACRO2 : MACRO1;
Upvotes: 2
Reputation: 6823
Yes, this code accomplishes exactly the same thing. It just depends on the logic used when writing the condition - so it can be chalked up to style (i.e. whichever is easier for you to think).
Upvotes: 6