Compiler Design Question

$$\text{Consider the following ANSI C code:}$$

int main(){
Integer x;
return 0;
}


$$\text{What will be the type of error?}$$

$$\text{a) Lexical}$$,

$$\text{b) Syntax}$$,

$$\text{c) Semantic}$$,

$$\text{d) None}$$ $$\tag {GATE-CS 2021}$$

According to me, Syntax Analysis phase should detect the error as there is no grammar in C which produces Integer x or in tokenized form id id. Any help is appreciated. :)

Your statement "Integer x;" is syntactically "identifier identifier;" which is a perfectly fine variable declaration. Semantically, the first identifier must be defined as a type, and the second identifier must not be defined as a variable in the same scope. The first condition fails, therefore ...

And you might download a copy of the C Standard to check if "int main()" is acceptable, or whether it must be "int main(void)", which is preferable and might be required.

In ANSI C syntax, as you say, there is no such construct as Integer, but only int. So your compiler should highlight a Syntax Error.

The grammar would be something as:

keyword = int | void | return | ...
expression = keyword id


Since expression won't match any keyword, the compiler stops at syntactic level.

• typedef struct test{ }tst; int main(void) { tst x; return 0; } Now this is valid in C, right? how is "tst x" resolved? Feb 27 at 3:22
• So you are creating an alias tst, At compile time, tst is added in the keywords for an expression. Or simply, the C compiler will do a lookup in the private keywords (and the lookup will fail since tst is not a standard keyword), and then in the user-defined keywords (and it will succeed). As you said it is valid syntax in C. Simply the tst struct is added at compile time among the set of keywords. So during lookup-time, C compiler will find it and assign it to a variable "x" (according to your syntax) Feb 27 at 9:16
• "id id; " is a syntactically correct variable declaration. No syntax error. Mar 1 at 14:38
• Oh yeah, the second one you are totally right. My bad Mar 4 at 10:29

But unless we make sure that it is not a primitive data type, how can an error be detected? A syntax analyzer cannot differentiate between keyword and identifier right? only Semantic analyzer can do that once it realizes and reduces the statement into starting symbol, which is when we try to make sense of the program i.e. in semantic analysis phase?

The answer to this is most likely SEMANTIC ANALYSIS.

• Right answer for the wrong reasons. "int x;" syntactically and semantically right. "int64_t x;" right if the right header file is included. "Integer x;" syntactically right, but semantic error. "for x;" = syntax error. Mar 1 at 14:46