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 is defined in as returning a value of type , which is an unsigned int. The output of the program is __________ .
View worked solution
Answer: 3
To find the output of the program, let's trace the execution step-by-step:
- In the
main()function, we have:x = "abc", sostrlen(x) = 3y = "defgh", sostrlen(y) = 5
- We call
printlength(x, y), wherespoints to"abc"andtpoints to"defgh". - Inside
printlength, we have:unsigned int c = 0; int len = ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t); - The function
strlenreturns a value of typesize_t, which is an unsigned integer type.- When we perform
strlen(s) - strlen(t), we are subtracting two unsigned integers: . - In unsigned arithmetic, does not result in . Instead, it underflows to a very large positive value:
- When we perform
- The comparison
(strlen(s) - strlen(t)) > cbecomes: Since this inequality is true, the ternary operator selects the first expression:strlen(s). - Thus,
lenis assigned the value ofstrlen(s), which is3.
The program prints 3.
Free practice · Your answers on this page are not saved.
