Skip to content
GATEiit

GATE CSE 2017 Session 1 Q63: printlength with unsigned strlen difference: output for "abc" and "defgh"

Syllabus topic: Programming in C

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

Try it: numerical answer: type the value

Numerical answer. No negative marking.
Show answer and explanation

Answer: 3 (official GATE 2017 final answer key)

Concept used: Subtracting unsigned values never gives a negative number: 3 − 5 wraps around to a huge positive unsigned value.

Concept notes

Loading notes…

First step: Work out the type and value of strlen(s) − strlen(t) for "abc" and "defgh", and decide which branch of the conditional is taken.

Full step-by-step solution

Loading…

Answer from the official final answer key. Found a mistake? Use Report issue and we will fix it.

More questions on Programming in C

Every PYQ on this topic →

Share this question

WhatsAppDownload image

Source: official GATE 2017 Session 1 CS question paper and final answer key, organised by IIT Roorkee. Question paper · Answer key