尤达条件和整数提升
当将大于 int
的类型与整数常量进行比较时,我应该将常量放在左侧还是右侧以确保执行正确的比较?
int64_t i = some_val;
if (i == -1)
或者应该是:
if (-1 == i)
是否存在任何情况与 -1LL
的比较不同(其中 int64_t
是 long long
)?
When comparing a type larger than int
, with an integer constant, should I place the constant on the left or the right to ensure the correct comparison is performed?
int64_t i = some_val;
if (i == -1)
or should it be:
if (-1 == i)
Are there any circumstances in which either case is not identical to comparison with -1LL
(where int64_t
is long long
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无论您将其放在右侧还是左侧,都没有关系;
==
运算符是完全对称的。如果
==
运算符的两个操作数都具有算术类型(如本例所示),则应用“常规算术转换”(C99 §6.5.9)。在这种情况下,适用的规则是:因此 -1 被转换为
int64_t
。-1LL
没有区别。It doesn't matter whether you put it on the right hand side or the left hand side; the
==
operator is completely symmetrical.If both operands to the
==
operator have arithmetic type, as in this case, then the "usual arithmetic conversions" are applied (C99 §6.5.9). In this case, the rule that applies is:So the -1 is converted to
int64_t
.-1LL
makes no difference.