GATE / CS ARCHIVE

GATE CSE 2017 SET 1 / QUESTION 53

GATE CSE 2017 Set 1 Q53

Programming in C · Expressions, Operators & Types · Full GATE CSE 2017 Set 1 paper

GATE 2017 Set 1, Q53 2 marks · NAT
Report issue

Expressions, Operators & Types

Question 53, GATE 2017: Source includes stdio.h and 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); }
The question explicitly says size_t, returned by strlen, is unsigned int. What is printed?
Tap to enlarge
Answer & solution

Official answer: 3.0

Our answer: 3

1. strlen("abc")=3 and strlen("defgh")=5. The stipulated return type is unsigned int, so subtraction is unsigned rather than signed.

2. Let the unsigned modulus be U=UINT_MAX+1. Then 3−5 wraps to U−2, a large positive value, not signed −2. The comparison is against unsigned c=0 and is therefore true.

3. The conditional selects strlen(s)=3. Conversion of 3 to int is representable and printf prints 3. The surprising result comes from unsigned subtraction; the printed void main is a separate source portability issue.

void main is a nonstandard hosted-C entry point; the exam assumes an implementation accepting it.

Original paper, page 23 · Answer key