Please help me in understanding the following code
Code:main() { signed int bit=512, i=5; for(;i;i--) { printf("%d\n", bit >> (i - (i -1))); } }
Please help me in understanding the following code
Code:main() { signed int bit=512, i=5; for(;i;i--) { printf("%d\n", bit >> (i - (i -1))); } }
What I would recommend is going through this line by line, and recording what the value of i is each time. 512 is 1000000000 in binary, and the >> operator shifts all the bits to the right by the number of places specified as the second operand ( i - (i - 1) ) in this case.
So it's going to print decreasing powers of two, starting with 10. But to see why, you ought to trace through the program as I suggested.
If you are using that code to learn, then you are in for a world of hurt. Learn from better code.Code:#include <stdio.h> // This was missing. It is needed for printf() int main(void) // The way main() was declared was wrong. { signed int bit=512, i=5; // Integers are signed by default, so this is redundant for(;i;i--) // Loop while i does not equal 0. Every iteration of the loop, subtract 1 from i. { printf("%d\n", bit >> (i - (i -1))); // (i - (i - 1)) always equals 1, so it is pointless. // The above line prints out bit shifted right 1 time. } return 0; // main returns an integer }
bit∙hub [bit-huhb] n. A source and destination for information.
Thanks to both of you especially bithub for the comments...........................