3

Is this a valid / sound way of resetting a counter if a condition is not met? It is the most compact way I could think of.

int counter = 0;
int a,b;

// Do .. and assign a and b 

counter = ((a<b) ? counter++ : 0); 
Three Diag
  • 585
  • 2
  • 7
  • 21
  • 1
    The aim should be to write this in the most maintainable way possible not the most compact way possible. – shuttle87 Aug 25 '15 at 15:46
  • You might also consider resetting or incrementing `counter` wherever you would be setting `condition`. – alcedine Aug 25 '15 at 16:07

2 Answers2

8

You are already assigning to counter, so don't use ++ as well.

counter = condition ? (counter + 1) : 0;
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Doesn't it produce the same result? – Three Diag Aug 25 '15 at 15:39
  • 1
    No. `counter++` evaluates to the *current* value of `counter`, then increments it. You would be assigning the old value of `counter` back to `counter` after you've incremented. I *think* you could use `++counter` as a hard-to-read-but-correct variant, but it's much clearer to simply use the side-effect-free `counter + 1`. – chepner Aug 25 '15 at 15:41
  • And if one wants to write really fancy code, just do counter += condition * 1; – SergeyA Aug 25 '15 at 16:32
  • @chepner: You might be assigning the old value of counter back to counter, or you might be assigning 42 to it. It's UB, and I'm pretty sure that `i = ++i` is also UB. – rici Aug 26 '15 at 04:42
  • I realized having multiple side effects on the RHS was UB (e.g., `x = i++ + ++i`), but couldn't remember if the RHS was defined to be fully evaluated prior to assigning to the LHS. I'd say it's something to avoid as confusing even if it were well-defined. – chepner Aug 26 '15 at 15:28
3

The behaviour of counter = (condition ? counter++ : 0); is undefined as there's no sequencing point. (The ternary is not sequenced, and neither is assignment).

It's similar in form to i = i++;

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78