edited by
24,715 views
102 votes
102 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

2 votes
2 votes
0 votes
0 votes
5 is the answer because ((3-5)>0 ) return 0 so len=strlen(t).

 

#include<stdio.h>
int main(){
    printf("%d\n",((3-5)>0));
return 0;
}

niraj@niraj-Lenovo-B460:~/socket_programming$ gcc compare.c
niraj@niraj-Lenovo-B460:~/socket_programming$ ./a.out
0
0 votes
0 votes

answer is 3

x and y are pointers and points to string "abc" and "defgh" and printlength(x,y) is called ,now x and y's values means base address of string "abc" and "defgh" is copied to s and t respectively.

1-here c is declared as unsigned int so it can't store negative values.

2-strlen() function is used  to find the actual length of string.

strlen(s)==3 and strlen(t)=5

strlen(s)-strlen(t)=3-5=-2 (signed value) >0=?

Note-we can't compare signed value and unsigned value so we need to convert -2 into unsigned value with the help of 2's complement.

if we take int as 2 bytes(16 bits) then 2's complement value of -2 =216-2 =65534

hence we can say 65534>0 so length=strlen(s)=3

0 votes
0 votes
int len = ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t);

Means is strlen(s) - strlen(t) > 0?

If yes, choose stren(s). If no, choose strlen(t).

 

Mathematically, $3-5 = -2$

So, we choose strlen(t) under normal circumstances.

 

But, as given in the question, strlen is an unsigned int. Unsigned int $-$ unsigned int can't be signed. Depending on the implementation (out of the scope of this question) the value of $3-5$ would be decided. It is however absolutely sure that the value won't be negative.

Hence, strlen(s) - strlen(t) > 0? Yes.
So, choose strlen(s) which is 3.

Answer:

Related questions

68 votes
68 votes
5 answers
1