不使用运营商'?' 正常吗?

use*_*453 0 c++ return operator-keyword

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

(freq>max_freq) ? return max_freq : ((freq<min_freq) ? return min_freq : return freq);
Run Code Online (Sandbox Code Playgroud)

但我得到的是

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’
Run Code Online (Sandbox Code Playgroud)

那么,是因为在这里使用返回是一件愚蠢的事情,我应该采取其他方式或者它可以工作,但我搞砸了?我很好奇,因为我觉得我用过'?' 操作员作为更整洁的if-else用于很多东西,它总是工作正常.有人能解释为什么会这样吗?

Ree*_*sey 6

您需要在三元运算符之前移动返回:

return (freq>max_freq) ? max_freq : ((freq<min_freq) ? min_freq : freq);
Run Code Online (Sandbox Code Playgroud)

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