Help

This is a discussion on Help within the C Programming forums, part of the General Programming Boards category; Please help me in understanding the following code Code: main() { signed int bit=512, i=5; for(;i;i--) { printf("%d\n", bit >> ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    46

    Help

    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)));
      }
    }

  2. #2
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    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.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,265
    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 
    }
    If you are using that code to learn, then you are in for a world of hurt. Learn from better code.
    bit∙hub [bit-huhb] n. A source and destination for information.

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    46
    Thanks to both of you especially bithub for the comments...........................

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21