0

The output for the code is 3? Please explain.According to me it should be 5.After removing "unsigned" still i got the output as 3.

 #include<stdio.h>
 #include<string.h>
 void main(){
    unsigned int c=0;
    int len;
    char x[20]="abc";
    char y[20]="defgh";
     if((strlen(x)-strlen(y))>c)
         len=strlen(x);
     else
        len=strlen(y);
    printf("%d",len);

}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Surya Lohia.
  • 446
  • 4
  • 16

2 Answers2

4

Because size_t is unsigned in C. So the comparison being negative yields a positive number. (sign extended bits of signed number yields a large value in unsigned case). Then that value is compared with 0 - being true it enters the first condition. Outputs 3.

Even if you remove unsigned from C that result of the strlen substraction yields a positive number much larger than 0. That's why you always get 3.

user2736738
  • 30,591
  • 5
  • 42
  • 56
3

After removing "unsigned" still i got the output as 3.

It is unimportant whether the variable c is declared as unsigned or signed

unsigned int c=0;

The problem is that the standard function strlen returns an object of the type size_t that is by definition is unsigned type.

size_t strlen(const char *s);

So in this expression

strlen(x)-strlen(y)

the result is interpreted as unsigned integer value. As strlen( x ) is less than strlen( y ) then you will get a very big unsigned value or at least a non-zero positive value.

Instead you could write

 if( strlen(x) > strlen(y) )
     len=strlen(x);
 else
    len=strlen(y);

And it would be more correctly to declare the variable len as having the type size_t.

size_t len;
//...
printf("%zu\n",len);
        ^^^
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335