Wednesday, January 16, 2008

Interesting C Program -22

Hi all,
This month's LFY had an interesting C Program that caught my attention. Lets discuss that in detail.

I have the following C Program.

#include "stdio.h"
int main()
{
struct value
{
int val:1;
};
struct value x;
x.val = 1;
printf("%d",x.val);
return 0;
}




What could be the output of the following Program?

I too thought that the output would be 1. But its not 1, but -1. Why?


The explanation goes like this.

The structure member has been declared "int", which is "signed int"

We all know that the MSB of a signed int will be the sign bit. If it is 1 then the number is negative and if it is zero the number is positive.

Right, now my question is, if the val takes the MSB ie. in binary format 1000 0000 0000 0000, which should be a -0. If the val takes LSB ie. in binary format 0000 0000 0000 0000, which should return 1. Why is it printing -1?


The explanation goes like this.

Any signed integer will be represented in its two's complement form.

Try out the following program.

#include "stdio.h"
#include "math.h"
void func(int x);
int main()
{
int x=-10;
func(x);
return 0;
}
void func(int x)
{
unsigned char x1;
signed int i;
for(i=15;i>=0;i--)
{
x1 = ((x/(unsigned int)pow(2,i))%2)+0x30;
printf("%c",x1);
}
}


This will print -10 in binary format. If you look at it, you will get "1111111111110110", which is two's complement of 10.


So the output, 1000 0000, will be printed in two's complement form, which is 1000 0001. This is signed integer. So outputs -1 instead of 1.

Search Google

Books that I refer to...

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