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 s="abc"s = \text{"abc"} and t="defgh"t = \text{"defgh"}.
Their lengths are:

strlen(s)=3\text{strlen}(s) = 3
strlen(t)=5\text{strlen}(t) = 5

The function strlen returns a value of type size_t, which is an unsigned integer type.
Consider the expression:

strlen(s)−strlen(t)=3−5\text{strlen}(s) - \text{strlen}(t) = 3 - 5

Because both operands are unsigned, the subtraction is performed in unsigned modular arithmetic. In 32-bit unsigned arithmetic:

3−5=232−2=42949672943 - 5 = 2^{32} - 2 = 4294967294

Next, this large unsigned integer is compared with unsigned int c = 0:

((4294967294)>0)((4294967294) > 0)

This comparison evaluates to TRUE (1).

The ternary operator selects the true branch:

len=strlen(s)=3\text{len} = \text{strlen}(s) = 3

Thus, printf("%d\n", len) prints 3.

Final answer

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.