在if语句中使用位移变量-是否出错 [英] using bit shifting variables inside if statement - error or not

查看:121
本文介绍了在if语句中使用位移变量-是否出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一些变量x和y,以及以下涉及位移的if语句:

Suppose we have some variables x and y, and the following if statement which involves bit shifting:

if (x<<y)

我已经阅读了一些文章,这些文章还涉及对变量(某种类型)和if语句内部使用位移位的问题,但是不幸的是,我无法得出明确的结论,无论是错误还是错误.不是.

I've read some posts which also deal with the issue of using bit shifting with variables (of some type) and inside if statement, but unfortunately I haven't been able to reach a unequivocal conclusion whether it is an error or not.

我假设,如果这是一个错误,那就是语义错误或运行时错误.

I assume that if it is an error, then it's a semantic error or a run-time error .

但这必然是错误的吗?

推荐答案

如果x是无符号整数类型,且至少等于unsigned int,并且y小于x的类型,则上面的部分语句将测试是否设置了x中顶部y没有的位.如果x是带符号类型或较小的无符号类型,则C89标准将要求实现也具有相同的行为,但需注意的是,将较小的带符号类型的最高位设置为设置了所有其他位.但是,C99和更高版本的标准将不需要实现有效地处理x非零但表达式x<<y将产生零的任何情况,除非x是无符号整数类型(至少与它一样大)为unsigned int.

If x is of an unsigned integer type that is at least as large as unsigned int, and y is less than the number of bits in x's type, then the above partial statement will test whether bits in x that aren't in the top y are set. The C89 Standard would require that implementations behave likewise if x is of a signed type or a small unsigned type, with the caveat that setting the top bit of a small signed type is regarded as setting all bits beyond. The C99 and later standards, however, wouldn't require that implementations usefully process any situation in which x is non-zero but the expression x<<y would yield zero, unless x is an unsigned integer type at least as large as unsigned int.

这篇关于在if语句中使用位移变量-是否出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆