Question

Consider the following C function definition.

int fX(char *a){
    char *b = a;
    while(*b)
        b++;
    return b - a;}

Which of the following statements is/are TRUE?

Choose every correct option
Official answer and solution
Official answer
A, B and D
From
Official GATE 2024 answer key

Solution

Observe that fX only reads the null-terminated string without modifying it, and computes its length via pointer subtraction b - a.

The function fX(char *a) is a standard implementation of strlen: it initializes b = a, increments b until *b == '\0', and returns the number of characters b - a.

  • Because fX only reads characters through b and never writes to *b or *a, passing a string literal directly (fX("abcd") in A), a modifiable character array (char c[] = "abcd" in B), or a pointer to a string literal (char *c = "abcd" in D) is completely valid and always returns 4.
  • The function compiles without any error (C is FALSE).
Final answer

Options (A), (B), (D)

Common trap

Thinking that passing a string literal to char *a causes undefined behavior even when the function never modifies the string.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2024 Computer Science and Information Technology - Set 2 (CS2)
Question
33 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.