Thursday, December 13, 2007

Interesting C Program -21

My friend came to me with the following weird C puzzle.


#include "stdio.h"
int main()
{
int x = 5;
printf("%f",x);
return 0;
}

This program throws me the following warning:

double format, different type arg (arg 2)


and the output is 0.000000

What is this?
His arguement was like this. Though my compiler allocates 4 bytes for both integer and float datatypes, why am I not being able to retrieve the same value if I interchange the types?

Yes, very good question.

The explanation goes like this.

The data will be retrieved from a variable in the way it is stored. If you retrieve it in a way different from the way it is stored, you will not be able to get the same value you have stored.

Lets be a bit more clear.

I am going to show you how the variables are stored in the memory.

Observe the following program.

#include "stdio.h"
int main()
{
int x=800;
int *x_int_ptr = &x;
unsigned char *x_char_ptr = (unsigned char *)x_int_ptr;
printf("%x %x %x %x",*(x_char_ptr+3),*(x_char_ptr+2),*(x_char_ptr+1),*(x_char_ptr));
return 0;
}


The output is 0 0 3 20

What is this?
Yes, the integer will be stored in the local memory like this. The equivalent of Integer Decimal 800 is Integer Binary 0b0000 0000 0000 0000 0000 0011 0010 0000.
But a character can store only 8 bits. So the higher byte 0000 0011 is stored as 3 in the second LS byte of output and the lower byte 0010 0000 which is 20 is stored in the first LS byte.

An integer 800 is stored like this.

Lets see how a float is stored.


#include "stdio.h"
int main()
{
float x=800;
float *x_int_ptr = &x;
unsigned char *x_char_ptr = (unsigned char *)x_int_ptr;
printf("%x %x %x %x",*(x_char_ptr+3),*(x_char_ptr+2),*(x_char_ptr+1),*(x_char_ptr));
return 0;
}



The ouput is 44 48 0 0

If we retrieve this value like an integer, how can we expect a correct result?
Let me justify the output 44 48 0 0.
This storage in memory is based on IEEE754 standard.

Just go the following link.
http://babbage.cs.qc.edu/IEEE-754/32bit.html

There you will find a calculator which takes this hex value as input and computes the decimal value that is given as input.

Just type 44480000 in field adjacent to Hexadecimal Representation, and you will be seeing the 800 in the field adjacent to Decimal Value Entered:.

So you need to be very careful while storing and retrieving data.


Isnt this program weird?

No comments:

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language