Three Diag
Three Diag

Reputation: 585

Ternary operator and increment operator

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

Upvotes: 3

Views: 1844

Answers (2)

P45 Imminent
P45 Imminent

Reputation: 8601

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++;

Upvotes: 3

chepner
chepner

Reputation: 532238

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

counter = condition ? (counter + 1) : 0;

Upvotes: 8

Related Questions