2

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"?

Doug Molineux
  • 12,283
  • 25
  • 92
  • 144

3 Answers3

6

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).

RageD
  • 6,693
  • 4
  • 30
  • 37
2

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.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • I agree, the weird thing is he / she consistently used it, sorry I had to mark the other answer as correct, just since he was first. :( thnx for the response tho – Doug Molineux Aug 10 '12 at 20:22
2

I prefer the second example as it is not using reverse logic, therefore easier to understand and less clutter.

myInt = myInt ? MACRO2 : MACRO1;
M3NTA7
  • 1,307
  • 1
  • 13
  • 25