Doug Molineux
Doug Molineux

Reputation: 12431

Unusual use of the Ternary Operator

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

Answers (3)

Ed Swangren
Ed Swangren

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

M3NTA7
M3NTA7

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

RageD
RageD

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

Related Questions