Ternary operator and increment operator

余生长醉 提交于 2019-12-23 17:12:01

问题


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

回答1:


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

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



回答2:


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



来源:https://stackoverflow.com/questions/32208229/ternary-operator-and-increment-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!