Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Issues in understanding output

 
Rachit Kumar Saxena
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
printf("%9d",9.6); gives a warning(I understand the warning) but the output is 858993459.Why?Please explain in terms of the memory architecture(I use a 32 bit system).
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
9.6 is a double literal. It's stored in memory in IEEE 754 double precision format. The printf function is going to interpret it as an integer, since you used d for the type.

The value 9.6 in double precision format looks like 858993459 when you interpret it as an integer.
 
Anand Hariharan
Rancher
Posts: 272
C++ Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper's answer is correct. Just wanted to clarify one statement in his post -
It's stored in memory in IEEE 754 double precision format.

Unlike Java, the language standards for C or C++ does not require the underlying implementation/hardware to use a floating point representation that conforms to the IEEE 754. However in practice, for the OP who uses a 32 bit system, and most other conventional desktops or laptops indeed conform to the IEEE 754 standard.

The takeaway is that, if one writes code that implicitly assumes a certain representation (like the OP's code for example), the C and C++ standards disavow such code claiming "undefined behaviour". This is because the interpretation of the underlying floating point representation as an integer could have unexpected weird effects in esoteric hardware (e.g., it could be a trap instruction).

Pay heed to the warnings!

- Anand
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic