Consider the following C program. #include<stdio.h> #include<string.h> void…

2017

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.ℎ as returning a value of type size_t, which is an unsigned int. The output of the program is __________ .

Attempted by 353 students.

Show answer & explanation

Correct answer: 3

Final output: 3

Explanation:

  • strlen("abc") is 3 and strlen("defgh") is 5.

  • strlen returns size_t, which is an unsigned type. The subtraction strlen(s) - strlen(t) is performed in unsigned arithmetic, so 3 - 5 wraps to a very large unsigned value (underflow).

  • That wrapped unsigned result is greater than the unsigned zero used in the comparison, so the condition is true, and the ternary operator selects strlen(s), which is 3.

  • The selected value 3 is stored in the int variable len and printed using printf("%d\n", len), producing the line:

3

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir