edited by
24,642 views
101 votes
101 votes

Consider the following C program.

#include<stdio.h>
#include<string.h>

void printlength(char *s, char *t) {
    unsigned int c=0;
    int len = ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t);
    printf("%d\n", len);
}

void main() {
    char *x = "abc";
    char *y = "defgh";
    printlength(x,y);
}

Recall that $strlen$ is defined in $string.h$ as returning a value of type $size\_t$, which is an unsigned int. The output of the program is __________ .

edited by

9 Answers

Best answer
135 votes
135 votes
$(strlen(s)- strlen(t)) = 3-5 =-2$

But in C, when we do operation with two unsigned integers, result is also unsigned. ($strlen$ returns $size\_t$ which is unsigned in most systems). So, this result "$-2$" is treated as unsigned and its value is $\textsf{INT_MAX}-2$ (not sure about all systems, but at least on systems using $2$'s complement representation). Now, the comparison is between this large number and another unsigned number $c$ which is $0$. So, the comparison return TRUE here.

Even if '$c$' is declared as "$int$", while doing an operation with an unsigned int, it gets promoted to unsigned int and we get the same result.

Hence $(strlen(s)- strlen(t)) >0$ will return $1$ on execution thus the conditional operator will return the true statement which is $strlen(abc) =3$.

Ans should be $3$.
edited by
12 votes
12 votes

Suppose  numbes are represented in 2's complement.

Then ,(strlen(s)- strlen(t)) gives -2.

Because it is unsigned ,its binary format will be in 2's complement 

+2n-1-2 on n bit machine.

Just care here about that it will be positive and  condition become true,and length of first string gets printed which is 3.

7 votes
7 votes
Since the question stresses that the function returns an UNSIGNED number. There has to be a thing around that. Which is

An unsigned number can never be negative and hence even the difference between two unsigned number also can't be negative. So when you subtract an unsigned number from another unsigned it would result in a positive wrapped around number.

Since positive number is greater than 0.

And hence we choose strlen('abc') which is 3.

Hence output is 3.
2 votes
2 votes

here it is taking two list of two legth

code like:

is the length of first list > lenght of 2nd list

then-> return the First list length

else

return 2nd list length

it is simply returning the length of larger string 

here it is 5

so 5 should be the answer

Answer:

Related questions

68 votes
68 votes
5 answers
1