The GATE Grind

GATE 2017 CS – Question 63

Programming and Data Structures · Programming in C · 2 marks · Numerical answer

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 ________.

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 3

Explanation

`strlen` returns an unsigned value, so $3 - 5$ does not give $-2$. It wraps around to a very large unsigned number, which is greater than $c = 0$. So the condition is true and `len` is `strlen(s)`, which is 3.