简体   繁体   中英

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.

Also, can you please tell me what this piece of code " i = i&1 " does? 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

At the begin of the for-Loop:

  • i is set to 5

Next step is: Check i--, which means:

  • First: i = 5 > 0 => true
  • Second: set i to i - 1 => i = 4

Next step: do the inner block.

Next step: i = i & 1, which results in:

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

Next step: Check i--

  • First: i = 0 => false
  • Second: set i to 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.

However, the program you've written is Undefined Behavior (error with g++). This is because you define i in the for loop, and once the loop ends, i goes out of scope. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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