Thread: Shift operators in C

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    3

    Smile Shift operators in C

    I was wondering why the following code returns the smallest integer?
    Code:
    int x;
    for(x=1; x>0; x<<=1);
    printf("%d",x);

    thanks.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    int in your case is signed. Thus, it ends up overflowing the variable, which wraps around to negative numbers. Oh, and it doesn't "return" anything. You don't have any return statements.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by jedi_jinn
    I was wondering why the following code returns the smallest integer?
    Code:
    int x;
    for(x=1; x>0; x<<=1);
    printf("%d",x);

    thanks.
    It will actually display the 'most negative' number possible for the int data type due to integer overflow.
    you should use 'unsigned int', however in order to display the number as unsigned, you need to use %u, not %d.

    Try searching the net for 'twos-complement' for more information on how computers store numbers.

  4. #4
    Registered User
    Join Date
    Jun 2004
    Posts
    201
    This only works on 2 complements systems.

    There is a sign magnitude system (of which I cant remember the name atm ) where loading the value 0x80000000 into a variable will crash your program. On that system the variable stands for -0. So dont write code liek this. If you want to know the minimum int value use INT_MIN or INT32_MIN with a C99 compiler
    Last edited by Laserve; 10-23-2006 at 01:10 AM.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    To further the point, signed overflow or underflow is undefined behavior.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bitwise shift operators in -ve numbers
    By rohit_second in forum C Programming
    Replies: 11
    Last Post: 09-15-2008, 01:18 PM
  2. still problems with ceasar shift
    By trevordunstan in forum C Programming
    Replies: 2
    Last Post: 09-14-2008, 01:49 AM
  3. Ceasar Shift program
    By trevordunstan in forum C Programming
    Replies: 11
    Last Post: 09-11-2008, 09:40 PM
  4. Bolean Operators hurt my head. (Trouble understanding) :(
    By Funcoot in forum C++ Programming
    Replies: 3
    Last Post: 01-20-2008, 07:42 PM
  5. Simulating Shift Key
    By PrimeTime00 in forum Windows Programming
    Replies: 7
    Last Post: 10-15-2004, 05:53 AM