繁体   English   中英

为什么 C 中的条件运算符在我的情况下不起作用?

[英]Why the conditional operator in C does not work in my case?

我有这段代码

 int8_t startPage = ( ((uint8_t)(ceilf( (float)CurrentY / 8))) - 1);
 /* variable = condition ? value_if_true : value_if_false*/
 startPage<0 ? 0:startPage;

如果CurrentY为 NULL,则startPage为 -1。 但是页面不能为负数。

所以我尝试检查它,如果 startPage 是否定的,则将其设置为 NULL。

但我有一个statement with no effect [-Wunused-value]

并且代码不起作用。 有任何想法吗?

startPage<0? 0:startPage; startPage<0? 0:startPage; 未使用,因此编译器会警告您。

您可以执行以下操作:

startPage = (startPage < 0) ? 0 : startPage;

startPage设置为0如果它小于0

表达式startPage<0? 0:startPage;的结果startPage<0? 0:startPage; 未分配给变量,因此未使用。 因此,编译器警告您有一条statement with no effect

反而,

startPage = startPage < 0 ? 0 : startPage;

将工作。 但是,如果您编写以下代码,则更具可读性:

if (startPage < 0) {startPage = 0}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM