简体   繁体   English

i = i&1 在 C 编程语言中是什么意思?

[英]What does i = i&1 mean in C programming language?

I got this sample code and I really do not understand how does it work.我得到了这个示例代码,我真的不明白它是如何工作的。 It is compiled by GCC and there are no errors at all.它是由 GCC 编译的,完全没有错误。

Also, can you please tell me what this piece of code " i = i&1 " does?另外,你能告诉我这段代码“ i = i&1 ”是做什么的吗? Thank you!谢谢!

int main(void){
  int i;
  for (i = 5; i--; i = i&1) {
    puts("iteration"); 
  }
  printf("%d\n",i);
  return 0;
}

Output of this program is:这个程序的输出是:

iteration迭代

-1 -1

At the begin of the for-Loop:在 for 循环的开始:

  • i is set to 5我设置为 5

Next step is: Check i--, which means:下一步是:检查 i--,这意味着:

  • First: i = 5 > 0 => true第一:i = 5 > 0 => 真
  • Second: set i to i - 1 => i = 4第二:将 i 设置为 i - 1 => i = 4

Next step: do the inner block.下一步:做内部块。

Next step: i = i & 1, which results in:下一步:i = i & 1,结果为:

  • 4&1 => 0100 & 0001 => i = 0 4&1 => 0100 & 0001 => i = 0

Next step: Check i--下一步:检查我--

  • First: i = 0 => false第一:i = 0 => false
  • Second: set i to i - 1 => i = -1第二:将 i 设置为 i - 1 => i = -1

&bitwise AND运算符

i = i&1 // this AND's bits of i to bits of value 1

i = i&1 will extract the least significant bit of i as & is the bitwise AND operator. i = i&1将提取的至少显著位i&bitwise AND运算符。

However, the program you've written is Undefined Behavior (error with g++).但是,您编写的程序是未定义行为(g++ 错误)。 This is because you define i in the for loop, and once the loop ends, i goes out of scope.这是因为您在for循环中定义了i ,一旦循环结束, i就会超出范围。 So printing it afterwards in the next line gives an error.所以之后在下一行打印它会出错。

Coming to your code, I would seriously love to know where you saw it, cause it seems horrible to me.来到你的代码,我很想知道你在哪里看到它,因为它对我来说似乎很可怕。 The conditions of the for loop seem convoluted, and I can't explain how the loop will run (which is probably not a good thing). for循环的条件似乎很复杂,我无法解释循环将如何运行(这可能不是一件好事)。

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

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