Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between lexical and syntax error

Tags:

c

parsing

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.

like image 753
sathish Avatar asked Jan 17 '16 03:01

sathish


People also ask

What is the difference between lexical and syntax?

Lexical analysis is the process of converting a sequence of characters into a sequence of tokens while syntax analysis is the process of analyzing a string of symbols either in natural language, computer languages or data structures conforming to the rules of a formal grammar.

What is the difference between syntax error?

Definition. A runtime error is a program error that occurs while the program is running. Whereas, a syntax error is an error in the syntax of a sequence of characters or tokens that is intended to be written in a particular programming language. Thus, this is the main difference between Run Time Error and Syntax Error.

What is lexical error in language?

Lexical error is an error that occurs when the learners. Wrong in choosing the words to use. It because they have a lack of. vocabulary or because of differences between mother tongue and target. language pattern.


1 Answers

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 ;-)

like image 70
chqrlie Avatar answered Sep 20 '22 19:09

chqrlie