-8

I cannot understand the output of this program:

void main(){
    double d=3.1416;
    char ch=*(char*)&d;
    cout<<ch;
    }

OUTPUT: 2

Note: The 2 is of much smaller size than the usual 2.

Can you please explain the meaning of line 3. Thank You.

kryptokinght
  • 539
  • 5
  • 12
  • What does your Note mean? Have you made any attempt to understand this yourself? – Scott Hunter Nov 02 '16 at 22:25
  • To print out the pointer address use `cout<<(void*)ch;`. That line is pretty meaningless from that context though. – πάντα ῥεῖ Nov 02 '16 at 22:26
  • Do you mean the 2 you're seeing is a superscript 2? – Catsunami Nov 02 '16 at 22:27
  • 7
    You can't learn `C++` by picking up random pieces of code that you don't understand and asking people on the internet to explain them. You need to apply yourself to a course or a book that explains everything from the beginning. Recommended books: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Galik Nov 02 '16 at 22:32
  • Yes, the 2 is a superscript of 2. – kryptokinght Nov 02 '16 at 22:32

1 Answers1

1

In your statement:

char ch=*(char*)&d;  

You are performing the following:
1. Taking the address or location of the variable.
2. Creating a pointer of type character to point to the variable.
3. Dereferencing (converting the first location of the variable) to a type of character (no transformations have occurred yet.
4. Assigning the first memory location of d to a character type variable (no conversions yet).

You are then printing the value in ch.

If the value in ch is a printable value, you are in luck; however, I doubt it will be meaningful. Otherwise, you won't be able to see it.

If you want to convert or transform from internal representation to textual representation, use:

cout << d;

I highly recommend using a debugger on this code and view the memory location of variable d. Take the value and see if it is printable.

Edit 1:
The value printed in line 4 depends on how the value 3.1416 is stored in memory.

Since it is a floating point variable, we can guess that it is split into: sign, mantissa and exponent. The big question, is how many bits are dedicated to the three groups. Usually, one bit is the sign. The others depend on your platform. If the char type on your platform is 8 bit, and the order is mantissa, exponent, then sign, your character will be the first 8 bits of the mantissa, which is probably not a printable character.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154