Consider the following C function definition. int fX(char *a){ char *b = a;…
2024
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?
- A.
The function call fX(”abcd”) will always return a value
- B.
Assuming a character array c is declared as char c[] = ”abcd” in main(), the function call fX(c) will always return a value
- C.
The code of the function will not compile
- D.
Assuming a character pointer c is declared as char *c = ”abcd” in main(), the function call fX(c) will always return a value
Attempted by 92 students.
Show answer & explanation
Correct answer: A, B, D
Answer: The following statements are true:
The function call fX(”abcd”) will always return a value
Assuming a character array c is declared as char c[] = ”abcd” in main(), the function call fX(c) will always return a value
Assuming a character pointer c is declared as char *c = ”abcd” in main(), the function call fX(c) will always return a value
Reason:
The function sets b to a and advances b while *b is non-zero; the loop stops when b points to the terminating null character '\0'.
When the loop ends, b points at the terminating null, so the expression b - a yields the number of characters before the null (the string length).
All three provided inputs are null-terminated strings, so the function returns 4 for these examples.
The code compiles in C: pointer arithmetic and the while(*b) check are valid. The claim that the code will not compile is false.
Note: Modifying a string literal is undefined behavior. This function does not modify the string, so passing a string literal to a function accepting char* is safe in C (though best practice is to use const char* if modification is not intended).
Concrete result: For the examples given, the function returns 4.
A video solution is available for this question — log in and enroll to watch it.