Question Details

Consider the following C statement:


char * str1 = ”Hello”; // stmt S

char * str2 = ”Hello”; // stmt S

char * str3 = ”Hello” // stmt S


Which of the following are correct?

Options

A

S1 and S2 are lexical errors

B

S2 is lexical and S3 is semantic

C

S2 is syntax and S3 is semantic

D

S1 is lexical and S3 is syntax

Show Answer

Correct Answer :

Option D

S1 is lexical and S3 is syntax

Solution :

The correct option is: S1 is lexical and S3 is syntax


Step-by-step Explanation:


1. Understanding Statement S1:
Let us examine the first statement:

char * str1 = ”Hello”;
Notice the quotation marks used around the string "Hello". They are curly/smart quotes (”...”) rather than the standard straight ASCII double quotes ("...") required by the C programming language.
A compiler's lexical analyzer (lexer) reads the source code character-by-character and groups them into valid tokens (such as keywords, identifiers, operators, and literals). Since the curly quote character ” is not a valid character/token in the C language character set, the lexical analyzer cannot recognize it. This results in a lexical error (also known as a scanner error or tokenization error). Thus, S1 contains a lexical error.


2. Understanding Statement S2:
The second statement is:

char * str2 = ”Hello”;
Just like S1, S2 also uses curly quotes (”...”) instead of standard straight ASCII quotes ("..."). Consequently, it would also trigger a lexical error for the same reason. However, looking at our correct option and choices, we focus on classifying S1 and S3.


3. Understanding Statement S3:
The third statement is:

char * str3 = ”Hello”
Notice that this statement does not end with a semicolon (;).
In C, a semicolon is a statement terminator required by the language's grammar rules. A syntax analyzer (parser) takes the sequence of tokens produced by the lexer and checks if they form valid grammatical structures according to the formal grammar of the language.
Because the terminating semicolon is missing at the end of the statement, the parser encounters a grammatical violation. This represents a syntax error. Thus, S3 contains a syntax error.


Conclusion:
S1 fails at the token level due to invalid characters (curly quotes), making it a lexical error.
S3 fails at the grammatical structure level due to a missing semicolon, making it a syntax error.
Therefore, the statement "S1 is lexical and S3 is syntax" is correct.

Unlock Our Free Library

Access expert-curated educational resources and study materials—completely free.

Ask AI Tutor
5 left
Q1 View Question & Options
AI Tutor is solving this question...
Reading question context & options...