Skip to content
Official PYQ · 2017

GATE CS 2017 Set 1 Q53 — Programming in C

Explain with AI

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 strlenstrlen is defined in string.hstring.h as returning a value of type size_tsize\_t, 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:

  1. In the main() function, we have:
    • x = "abc", so strlen(x) = 3
    • y = "defgh", so strlen(y) = 5
  2. We call printlength(x, y), where s points to "abc" and t points to "defgh".
  3. Inside printlength, we have:
    unsigned int c = 0;
    int len = ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t);
  4. The function strlen returns a value of type size_t, which is an unsigned integer type.
    • When we perform strlen(s) - strlen(t), we are subtracting two unsigned integers: 3−53 - 5.
    • In unsigned arithmetic, 3−53 - 5 does not result in −2-2. Instead, it underflows to a very large positive value: 3−5≡−2≡232−2=4294967294(on a 32-bit system)3 - 5 \equiv -2 \equiv 2^{32} - 2 = 4294967294 \quad \text{(on a 32-bit system)}
  5. The comparison (strlen(s) - strlen(t)) > c becomes: 4294967294>04294967294 > 0 Since this inequality is true, the ternary operator selects the first expression: strlen(s).
  6. Thus, len is assigned the value of strlen(s), which is 3.

The program prints 3.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions