没有正确使用操作员'?'?

Not using operator '?' properly?

本文关键字:操作员      更新时间:2023-10-16

所以我有函数返回一个整数以及它的一些最大值和最小值。我想在最后用漂亮干净的单行词来做:

(freq>max_freq) ? return max_freq : ((freq<min_freq) ? return min_freq : return freq);

但我得到的是

posplot.hh:238:21: error: expected primary-expression before ‘return’
     (freq>max_freq) ? return max_freq : ((freq<min_freq) ? return min_freq : return freq);}
                     ^
posplot.hh:238:21: error: expected ‘:’ before ‘return’
posplot.hh:238:21: error: expected primary-expression before ‘return’
posplot.hh:238:21: error: expected ‘;’ before ‘return’

那么,这是因为在这里使用 return 是一件愚蠢的事情,我应该以其他方式让它工作,或者它可以工作但我搞砸了?我很好奇,因为我想我已经使用"?"运算符作为更整洁的 if-else 用于很多东西,而且它总是工作正常。有人可以解释为什么会发生这种情况吗?

您需要在

三元运算符之前移动返回:

return (freq>max_freq) ? max_freq : ((freq<min_freq) ? min_freq : freq);

基本上,三元运算符应该在每个分支上计算为单个值(这意味着它需要 3 个表达式,并且您正在创建一个表达式和两个语句,因为return创建一个语句)。

条件运算符的操作数(与大多数其他运算符一样)必须是表达式而不是语句,因此它们不能是返回语句。

条件表达式本身有一个值:所选操作数的值。评估并返回它:

return (freq>max_freq) ? max_freq : ((freq<min_freq) ? min_freq : freq);

? 运算符可用于表达式中。 返回是一个语句

您的单行代码可能如下所示:

return (freq>max_freq ? max_freq : (freq<min_freq ? min_freq : freq));