Consider the following C statements:
char *str1 = "Hello; /* Statement S1 */ char *str2 = "Hello;"; /* Statement S2 */ int *str3 = "Hello"; /* Statement S3 */
Which of the following options is/are correct?
View worked solution
Answer: C
To determine the correct option, let's analyze each statement phase-by-phase during compilation:
-
Statement S1:
char *str1 = "Hello; /* Statement S1 */- The string literal starts with a double quote
"but is never closed on the same line. - In C, a string literal must be closed on the same line unless a backslash (
\) is used for continuation. - Because the lexical analyzer (scanner) cannot group these characters into a valid string token, this results in an unclosed string literal error, which is a lexical error.
- The string literal starts with a double quote
-
Statement S2:
char *str2 = "Hello;"; /* Statement S2 */- This statement is perfectly valid. The string literal
"Hello;"is correctly closed, and assigning it to achar *is type-compatible. There are no errors.
- This statement is perfectly valid. The string literal
-
Statement S3:
int *str3 = "Hello"; /* Statement S3 */- The tokens are lexically valid, and the statement is syntactically correct according to the grammar rules of variable declarations.
- However, during semantic analysis, the compiler performs type checking. Here, a string literal of type
char *is being assigned to a pointer of typeint *. - This incompatible pointer assignment (type mismatch) is a semantic error.
Thus, S1 has a lexical error and S3 has a semantic error.
Free practice · Your answers on this page are not saved.
