1

My book says lexical analysis detects reserved words.

How can lexical analysis detect whether we are using reserved words in incorrect places ?

For eg :- while(a>0) and int while = 5.

How can lexical anaylsis differentiate the usage of while in both the above examples based on the context?

Sagar P
  • 339
  • 3
  • 13

1 Answers1

1

Briefly, lexical analyzer reads source code character by character and generates tokens. It does not care about in what order tokens are generated. Relationship between tokens are checked by syntax analyzer and specified by a context free grammar. Let me give you a simple example. Consider the following piece of code

 int while = 5

Lexical analyzer emmits the following tokens:

KEYWORD (INT)
KEYWORD (WHILE)
ASSIGN (=)
NUMBER (5)

Then then syntax analyzer checks these tokens, detects (based on the corresponding CFG) that the keyword WHILE cannot be lvalue, and reports the syntax error. In fact the syntax analyzer expects IDENTIFIER after the token KEYWORD (INT).

fade2black
  • 9,905
  • 2
  • 26
  • 36