The Gateway to Computer Science Excellence
+1 vote
How will the compiler detect whether "if" is a keyword or an identifier?

Please tell me the concept behind this.
in Compiler Design by | 356 views
We are already stores the pattern of each keyword,

then when a lexeme found, then it will be compared by every pattern ( First all keyword patterns, after that only we compare with digits patterns and identifier patterns etc. )

@Shaik Masthan

can u pls give an example that describes and differentiate tokens, identifiers and lexemes


first we have patterns for every tokens in the language.

i mean,

identifiers = (letter).(letter+digit+underscore)*

numbers = (digit).(digit)*

comment start = " \* "

each keyword is a separate pattern


now, let take the source code :-

int a,b = 50 ;

lexeme :- find the consecutive words until match with a pattern

scans i

scans n

scans t

scans whitespace ===> when it is find a white space then make "int" as a lexeme.

check for pattern which it is matched, then declare it as keyword


scans a

scans comma(,) ===> when it is find a comma then make "a" as a lexeme.

check for pattern which it is matched, then declare it as identifier


continue this process....


@Shaik Masthan

Thanks for the valuable comment.

3 Answers

0 votes
keyword is one type of token , so it is already reserved.
0 votes

In some language like c, java etc keyword is specified so the compiler will detect the keyword in the lexical analysis phase.

While in some language like FORTAN keyword are not specified, it uses lookahead operator ( follow certain pattern before certainty of token for the keyword). These patterns are specified in Lex language (lexical analyzer generator).

Like for keyword the pattern are defined as in LEX language:

  IF / \  ( .*  \ ) { letter}       here for certainty of IF as keyword lookahead  (lookahead operator '/ ' ) certain pattern.

for more information follow book compiler design by ULLMAN.

0 votes
If it's asking

If is a keyword or identifier

Generally this type of question comes under ambiguity and will not be aked  in GATE exam but still

if (small letter)  -> identifier

IF (  capital letter's) -> keyword  [or 1st letter capital you can say it's a keyword ]

there is no such rule but always works

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
52,375 questions
60,595 answers
95,409 users