sathish
sathish

Reputation: 153

Difference between lexical and syntax error

int 2ab;
int 2;

For above declarations, please tell which one is a lexical error and a syntax error in the C language. I am confused in both the declarations.

Upvotes: 7

Views: 11087

Answers (1)

chqrlie
chqrlie

Reputation: 144685

Both declarations are invalid, so you are rightfully confused, but for different reasons:

  • A lexical error occurs when the compiler does not recognize a sequence of characters as a proper lexical token. 2ab is not a valid C token. (Note that 2ab is a valid C preprocessing token that can be used in token pasting macros, but this seems beyond your current skill level).

  • A syntax error occurs when a sequence of tokens does not match a C construction: statement, expression, preprocessing directive... int 2; is a syntax error because a type starts a definition and a number is not an expected token in such a context: an identifier or possibly a *, a (, a specifier or a qualifier is expected.

Note that qualifiers and type or storage specifiers can appear in pretty much any order in C declarations:

int typedef const long cint;       // same as typedef const long int cint;
int volatile static short x;       // same as static volatile short int x;
int long unsigned long extern ll;  // same as extern unsigned long long int ll;

The above valid declarations are examples of variations you should not use ;-)

Upvotes: 13

Related Questions