thoughts, ideas, code and other things...

Wednesday, June 06, 2007

Truth, in C

Now in C, boolean data-type doesn't exist. Instead we use integers for the purpose. Conventionally 0 is false, and anything other than 0 is true. So,

if (32)
printf ("This will always be printed\n");
if (0)
printf ("This will never get printed. \n");
In the above code-snippet, its obvious that output is "This will always be printed".
Lets have another one -

int j, j;
j = 5;
i = i > 45;
pintf ( "i = %i" , i );
No here, the logic "i>45" will get evaluated and result stored in i. So, since j isn't actually greater than 45, i will contain 0. Had j been of the value 46 or 100 , i will get assigned 1.

Inside stuff :
Okay this is about C. What about how computer decides true/false?
The answer is yet interesting, what a computer actually does is that it sees everything in binary number system. So, a zero will always look like
0 or 000000 or 0000000000000
and anything other than a zero is bound to have the digit '1' at at least one place in the binary equivalent. So, the machine just sees if all the bits are 0, if thats the situation, it means FALSE. If even a single one is encountered, it means TRUE.

So how was it ?



Post a Comment

Subscribe to Post Comments [Atom]

<< Home