当前位置: 动力学知识库 > 问答 > 编程问答 >

c - What is the logic behind the control statement 'if((i+j) & 1)'?

问题描述:

This program declares an 8x8 character array and then uses a loop to store the following data into the array(one character per array element). Then it prints this array to the screen:

BRBRBRBR

RBRBRBRB

BRBRBRBR

RBRBRBRB

BRBRBRBR

RBRBRBRB

BRBRBRBR

RBRBRBRB

The program works fine. However, I am having trouble understanding the logic behind the if statement:

if((i+j) & 1)

I don't understand how if adding i + j 'and' 1 is true set array to 'R' else set it to 'B'. This might have a rather obvious answer, but I am new to C. Can someone help clarify why this program works with this logic? Thank You!

#include <stdio.h>

#include <stdlib.h>

int main(void)

{

int i, j;

char letter[8][8];

for(i=0; i<8; i++) {

for(j=0; j<8; j++) {

//This if-statement

if ((i+j) & 1)

letter[i][j] = 'R';

else

letter[i][j] = 'B';

printf("%c" , letter[i][j]);

}

printf("\n");

}

return 0;

}

网友答案:

(i+j) & 1 will evaluate to true when i+j is odd and false when i+j is even.

The & in that expression is the bitwise AND operator, not the logical AND operator.

The code would be so much more readable if written as:

int is_odd(int n)
{
   return ((n&1) == 1);
}

...

if ( is_odd(i+j) ) 
网友答案:

There's a pattern here - the last bit of the value is constantly flipped:

i = 0, j = 0 --> i + j = 0 --> 2'b00
i = 0, j = 1 --> i + j = 1 --> 2'b01
i = 0, j = 2 --> i + j = 2 --> 2'b10
...and so on

The & operator then does a bit-wise and operation on the bits of the value:

//this evaluates to false, and 'B' is printed
2'b00 & 1 == 2'b00 & 2'b01 == 2'b(0&0)(0&1) == 2'b00 
//this evaluates to true, and 'R' is printed
2'b01 & 1 == 2'b01 & 2'b01 == 2'b(0&0)(1&1) == 2'b01 
分享给朋友:
您可能感兴趣的文章:
随机阅读: