三元运算符和自增运算符

Ternary operator and increment operator

本文关键字:运算符 三元      更新时间:2023-10-16

如果不满足条件,这是复位计数器的有效/合理的方法吗?这是我能想到的最紧凑的方法。

int counter = 0;
int a,b;
// Do .. and assign a and b 
counter = ((a<b) ? counter++ : 0); 

您已经分配给counter,所以不要再使用++

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

由于没有排序点,counter = (condition ? counter++ : 0);的行为未定义。(三元数没有排序,赋值也没有排序)。

形式与i = i++;相似