Question
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 ______.
Official answer and solution
- Official answer
- 3
- From
- Official GATE 2017 answer key
Solution
Evaluate the subtraction of two size_t unsigned values and trace the condition in the ternary operator.
The strings passed to printlength are and .
Their lengths are:
The function strlen returns a value of type size_t, which is an unsigned integer type.
Consider the expression:
Because both operands are unsigned, the subtraction is performed in unsigned modular arithmetic. In 32-bit unsigned arithmetic:
Next, this large unsigned integer is compared with unsigned int c = 0:
This comparison evaluates to TRUE (1).
The ternary operator selects the true branch:
Thus, printf("%d\n", len) prints 3.
3.0
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2017 Computer Science and Information Technology (CS) Session 1
- Question
- 53 of 65, printed as CS Q.53
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.