在函数 strToInt 中正确使用三元运算符 (C)
proper use of the ternary operator in a function strToInt (C)
for (minus == false ? i = 0 : i = 1; string[i] >= '0' && string[i] <= '9'; ++i)
{
intValue = string[i] - '0';
minus == false ? result = result * 10 + intValue :
result = result * 10 - intValue;
}
error: expression is not assignable
screenshot - http://share.pho.to/AarcJ
由于运算符优先规则,minus == false ? i = 0 : i = 1
将被解析为 (minus == false ? i = 0 : i) = 1
。在计算 minus == false ? i = 0 : i
后,运算符 =
的左侧将变为右值,但赋值运算符必须将左值作为其左操作数。
将其更改为 minus == false ? (i = 0) : (i = 1)
使用(举例)
for (i = minus? 1:0; string[i].... etc
还有...
result = result * 10 + minus? (-lastvalue) : lastvalue;
for (minus == false ? i = 0 : i = 1; string[i] >= '0' && string[i] <= '9'; ++i)
{
intValue = string[i] - '0';
minus == false ? result = result * 10 + intValue :
result = result * 10 - intValue;
}
error: expression is not assignable screenshot - http://share.pho.to/AarcJ
minus == false ? i = 0 : i = 1
将被解析为 (minus == false ? i = 0 : i) = 1
。在计算 minus == false ? i = 0 : i
后,运算符 =
的左侧将变为右值,但赋值运算符必须将左值作为其左操作数。
将其更改为 minus == false ? (i = 0) : (i = 1)
使用(举例)
for (i = minus? 1:0; string[i].... etc
还有...
result = result * 10 + minus? (-lastvalue) : lastvalue;