GATE CS 2024 Set 2 | Question 33

MSQ · 1 mark

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?

  1. Option A: The function call fX("abcd") will always return a value (correct)
  2. Option B: Assuming a character array c is declared as char c[] = "abcd" in main(), the function call fX(c) will always return a value (correct)
  3. Option C: The code of the function will not compile
  4. Option D: Assuming a character pointer c is declared as char *c = "abcd" in main(), the function call fX(c) will always return a value (correct)

Answer

(A), (B), (D)

Explanation

fX moves the pointer b forward until it reaches the terminating '\0' and returns b - a, the number of characters before it: the length of the string. The pointer difference is converted to int on return, so the function is valid C and (C) is false.

  • (A) A string literal is always stored with a terminating null character, so the call returns 4.
  • (B) char c[] = "abcd" creates a 5-element array whose last element is '\0', so the call returns 4.
  • (D) c points to the literal itself, which also ends in '\0', so the call returns 4.

The loop stops in every case, so all three calls return a value.

Answer: A, B, D