Thread: Getting surprising behavior when casting

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    127

    Getting surprising behavior when casting

    I'm trying to cast a float to an unsigned int and getting some surprising behavior.

    Code:
    float x = -1.0;
    unsigned int y = (unsigned int)x;
    printf("y = %d\n", y);
    The output of this code changes depending on which compiler I use. Sometimes I get -1 and sometimes I get 0. Not really sure why though.

    edit: Tried searching before posting but tried a different search term after posting and found a stackoverflow thread explaining why this is not portable. A bit surprising, but good to know.
    Last edited by homer_3; 03-18-2014 at 10:22 AM.

  2. #2
    Registered User
    Join Date
    Nov 2013
    Posts
    107
    What was the problem?

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    127
    The unsigned cast of a float. A signed cast works ok.

  4. #4
    Registered User
    Join Date
    Mar 2008
    Posts
    10
    If you want to print an unsigned int then you should use "%u" and not "%d". Maybe that's your problem.

    Regards.

  5. #5
    Registered User
    Join Date
    Nov 2013
    Posts
    107
    Anyone care to expand on this problem, i.e how negative integers/floats are cast into postive integers/floats? I feel there is a topic here..

  6. #6
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    O_o

    There really isn't much to explain. Well at least, there isn't much to explain in the direction you imagine.

    The compiler simply decided that, because an `unsigned' value can't be negative, the assignment could be skipped.

    As you noted, using a `signed' integer "works". Using code that trumps the optimizer--such as reading the value from `scanf'--also works.

    Oddly, the user gemera recently reference the issue in the other direction.

    Yep. The behavior completely conforms to the standard.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Different behavior of gcc 3.x and 4.x
    By Sean M in forum C++ Programming
    Replies: 10
    Last Post: 08-10-2012, 02:49 PM
  2. Surprising Segfault
    By sangamesh in forum C Programming
    Replies: 6
    Last Post: 04-26-2011, 02:49 PM
  3. Advantages of c++ type casting over c type casting
    By kaibalya2008 in forum C++ Programming
    Replies: 10
    Last Post: 05-05-2009, 11:09 AM
  4. Startling, but not surprising news report
    By LuckY in forum A Brief History of Cprogramming.com
    Replies: 3
    Last Post: 12-10-2004, 05:08 PM
  5. Casting operator behavior
    By pianorain in forum C++ Programming
    Replies: 9
    Last Post: 10-11-2004, 04:07 PM