Thread: what is wrong with the following code?

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    8

    what is wrong with the following code?

    Hi all,

    I am getting some garbage values when i executed this program.
    Code:
    void main()
    {
      float f;
      scanf("%f",&f);
      printf("%d", *((int *)&f));
    
    }
    i know this has some thing to do with the way floating point values are stored.
    but can somebody please explain what exactly is happening?

    thanks.

  2. #2
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    1. main() should return int.

    2. It's not garbage value, just a value that doesn't make much sense in decimal. Floats are represented differently in memory
    http://en.wikipedia.org/wiki/Single_precision

    and you are forcing the computer to interpret this bit-sequence as an int, which, as expected, doesn't make much sense.

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Code:
    printf("%d", *((int *)&f));
    You are casting the address of the float to an address of an integer and printing the address as a signed value. Just cast the float to an int and you'll be fine. In other words, get rid of the stars and and ampersand.
    Mainframe assembler programmer by trade. C coder when I can.

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    and printing the address as a signed value
    There is derefencing of the address - so the printed value is not the address but the float value, that is interpreted as integer...
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  5. #5
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Yep, I didn't take into consideration the effects of the first star. Thanks.
    Mainframe assembler programmer by trade. C coder when I can.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is wrong in this simple code
    By vikingcarioca in forum C Programming
    Replies: 4
    Last Post: 04-23-2009, 07:10 AM
  2. what is wrong with this code please
    By korbitz in forum Windows Programming
    Replies: 3
    Last Post: 03-05-2004, 10:11 AM
  3. I cant find what is wrong with this code
    By senegene in forum C Programming
    Replies: 1
    Last Post: 11-12-2002, 06:32 PM
  4. Anyone see what is wrong with this code?
    By Wise1 in forum C Programming
    Replies: 2
    Last Post: 02-13-2002, 02:01 PM
  5. very simple code, please check to see whats wrong
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-10-2001, 12:51 AM