right shifting

Discussion in 'C++' started by crookie, Nov 9, 2006.

  1. crookie

    crookie Guest

    if I have the foolowing code,

    main()
    {
    unsigned int i=34;
    i>>=32;
    }

    why does the value of i remain 34? I thought it should be a zero.
    (the g++ compiler gives me a warning about shifting >= size of variable.)
    crookie, Nov 9, 2006
    #1
    1. Advertising

  2. crookie

    Kai-Uwe Bux Guest

    crookie wrote:

    > if I have the foolowing code,
    >
    > main()
    > {
    > unsigned int i=34;
    > i>>=32;
    > }
    >
    > why does the value of i remain 34? I thought it should be a zero.
    > (the g++ compiler gives me a warning about shifting >= size of variable.)


    The standard [5.8/1] says about the shift operators:

    [...] The behavior is undefined if the right operand is negative, or
    greater than or equal to the length in bits of the promoted left operand.

    It would appear that on your platform sizeof(int)<=32, whence you have
    undefined behavior: anything could happen.


    Best

    Kai-Uwe Bux
    Kai-Uwe Bux, Nov 9, 2006
    #2
    1. Advertising

  3. crookie wrote:

    > if I have the foolowing code,
    >
    > main()
    > {
    > unsigned int i=34;
    > i>>=32;
    > }
    >
    > why does the value of i remain 34? I thought it should be a zero.
    > (the g++ compiler gives me a warning about shifting >= size of variable.)


    Because on your system, an unsigned int has 32 or fewer bits, and (as I
    recently learned) shifting by any number greater than or equal to the
    number of bits is Undefined Behavior. Which means that any value of i
    is equally valid.

    For more detail, see this thread from over the summer:

    http://tinyurl.com/y382v3

    Best regards,

    Tom
    Thomas Tutone, Nov 9, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. walala
    Replies:
    3
    Views:
    5,327
    Brent Hayhoe
    Nov 21, 2003
  2. Stefan Duenser

    Basic shifting question

    Stefan Duenser, Dec 7, 2004, in forum: VHDL
    Replies:
    4
    Views:
    440
    Stefan Duenser
    Dec 8, 2004
  3. Replies:
    3
    Views:
    342
    Roedy Green
    Dec 18, 2005
  4. crookie

    right shifting

    crookie, Nov 9, 2006, in forum: C Programming
    Replies:
    12
    Views:
    568
  5. Jack
    Replies:
    15
    Views:
    215
Loading...

Share This Page