GATE / CS ARCHIVE

GATE CSE 2024 SET 2 / QUESTION 33

A read-only string-length loop

Programming in C · Arrays & Strings · Full GATE CSE 2024 Set 2 paper

GATE 2024 Set 2, Q33 1 mark · MSQ
Report issue

Arrays & Strings

Question 33, GATE 2024: In C, fX(char *a) sets char *b=a, executes while(*b) b++, then returns b−a as int. Which claims are true? A fX("abcd") returns; B with char c[]="abcd", fX(c) returns; C the function does not compile; D with char *c="abcd", fX(c) returns.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A, B, D

Approach: Trace the pointer until the null terminator and distinguish reading a literal from modifying it.

1. Derivation. The pointer b advances until it reaches the terminating null byte and returns the element difference b−a, the string length. Each stated argument is a valid null-terminated four-character string, so each call returns 4. The function only reads characters; it does not modify string literals. Therefore A, B, D are true and the code is valid C. Pointer subtraction here is within the same array and the small result fits int.

2. Explanation and checks. The bytes at offsets 0,1,2,3 are a,b,c,d and are nonzero, so the loop advances four times. At offset 4 the terminating zero makes the condition false. Both pointers remain associated with the same character array, so subtraction gives four elements. The function never assigns through either pointer, and the supplied arguments are terminated, avoiding two common string errors. These are C examples; a stricter C++ string-literal type rule is not the language specified.

Options A, B and D print the string literal abcd between typographic quotation marks (”abcd”). These are read as ordinary ASCII string delimiters, and under that intended reading each call returns 4. The function definition itself contains no quotation marks and is valid C as printed; only the quote glyphs in the options, copied literally, would not form a C string literal.

Original paper, page 22 · Answer key