I share many reservations about the code shown in the mock test #1 for C at TutorialsPoint. Using code that is not valid for C99, let alone C11 or C17, is weird. Code from the last millennium should not still be being taught to new programmers — except as object lessons in how the language has changed since it was first standardized.
This SO question originally discussed Q3 of the mock test, but the SO question and primary answer have since been amended to remove the commentary on that one question.
The code for Q3 is:
#include<stdio.h>
main()
{
char s[]="hello", t[]="hello";
if(s==t){
printf("eqaul strings");
}
}
The arrays s
and t
must be at different locations; they are separate arrays, initialized by the same string, but still separate arrays and hence stored at separate addresses. The conditional compares the addresses at which the arrays are stored (string comparison would use strcmp()
or equivalent), and the arrays are stored at separate addresses so the result of the comparison is false.
- Consequently, the only correct answer is C — No Output.
- This is the answer given by TutorialsPoint in their key.
There was some discussion on SO of string literals and the fact that they can be stored in the same location. However, that discussion was misguided; it doesn't apply to this code. The strings used to initialize the arrays may be colocated, but the arrays themselves cannot be colocated. However, suppose that the definitions were of pointers, not arrays:
char *s = "hello", *t = "hello";
Now it is quite possible that s
and t
contain the same address, though it is also possible that they contain different addresses. (The addresses of s
and t
must be different; they're two separate pointer variables).
But the array initializers in the code in the question must initialize two separate arrays, and those separate arrays must be stored at separate addresses, and hence the comparison s == t
in the question must be false, so nothing is printed.