On Tue, Mar 4, 2008 at 12:01 PM, debasish deka
<[EMAIL PROTECTED]> wrote:
> Hello All,
>  A few days back I attended Huawei Interview where the following code's 
> output was expected:
>     unsigned char i;
>     for(i=0;i<2000;i++)
>          printf("\t%d",i);
>  A simple thinking gives the output to be :
>  values from 0 to 255.
>  When I checked it out on my Dev-C++ it showed counting exactly up to 2000.

You compiler isn't doing what it should then.

>  Now my doubt it if a character variable occupies one byte then it should 
> count upto 255 only

On most computers this is what it should be doing. (The exceptions
being when a char has more than 8 bits.)

>  then it should overflow. Thus the result should be either counting upto 
> 255(and stop)

Erm - nope.

> or ending  in an infinite loop counting each time up to 255.

That's what it should be doing.

> Then why and how it is counting uoto 2000 (exactly).

Pass. Your compiler may be broken.

>  Again in a forum it was asked to give the output of the following codes ::
>     unsigned i;
>     i=100*400;
>     printf("\n%d\n",i);
>  Strangely again, the output was exactly 40000as opposed to + 32767 or showing
> any sort or overflow, since the range of unsigned int ranges from- 32767 to 
> 32768.

That is one possible range. The Standard dictates minimum ranges only
- compilers are allowed to exceed them.

>  Now my question is how the compiler manages to tackle such situations, I 
> mean what
> mechanism does the compiler the aplies in such a situation...

Depends on your compiler, and the value of CHAR_BIT (8 on my system.)
I get the following:

[EMAIL PROTECTED] tmp]# cat t.c
#include <stdio.h>

int main(void){
        unsigned char c;
        for(c=0; c<4000; c++){
                printf("%i\n", c);
        }
        return 0;
}

[EMAIL PROTECTED] tmp]# make t
cc     t.c   -o t
t.c: In function 'main':
t.c:5: warning: comparison is always true due to limited range of data type

Note the warning.

And running t gives me cycles of 0-255 then it starts at 0 again, and
goes on forever.



-- 
PJH

http://shabbleland.myminicity.com

Reply via email to