3

What is the difference between these two errors, lexical and semantic?

int d = "orange";
inw d = 4; 

Would the first one be a semantic error? Since you can't assign a literal to an int? As for the second one the individual tokens are messed up so it would be lexical? That is my thought process, I could be wrong but I'd like to understand this a little more.

user181421
  • 57
  • 3
  • 11

1 Answers1

8

There are really three commonly recognized levels of interpretation: lexical, syntactic and semantic. Lexical analysis turns a string of characters into tokens, syntactic builds the tokens into valid statements in the language and semantic interprets those statements correctly to perform some algorithm.

Your first error is semantic: while all the tokens are legal it's not legal in Java to assign a string constant to a integer variable.

Your second error could be classified as lexical (as the string "inw" is not a valid keyword) or as syntactic ("inw" could be the name of a variable but it's not legal syntax to have a variable name in that context).

A semantic error can also be something that is legal in the language but does not represent the intended algorithm. For example: "1" + n is perfectly valid code but if it is intending to do an arithmetic addition then it has a semantic error. Some semantic errors can be picked up by modern compilers but ones such as these depend on the intention of the programmer.

See the answers to whats-the-difference-between-syntax-and-semantics for more details.

Community
  • 1
  • 1
sprinter
  • 27,148
  • 6
  • 47
  • 78
  • 1
    @Sprinter Shouldn't the first line be a semantic error? http://www.tutorialspoint.com/compiler_design/compiler_design_semantic_analysis.htm – Samuel Kok Sep 16 '16 at 02:27
  • that's what was confusing me since I had read something similar before. – user181421 Sep 16 '16 at 02:30
  • 1
    Since the first line is grammatically correct (All tokens are valid symbols in java) but it doesn't make sense for java to assign a string to an integer. It should be a semantic error. – Samuel Kok Sep 16 '16 at 02:31
  • 1
    Its also important to note that whatever a compiler detects doesn't equate a syntax error. Since most compilers now are able to perform type checking, which from a compiler design point of view, is a semantic error. It is also mentioned in the answer that is linked. – Samuel Kok Sep 16 '16 at 02:54
  • @SamuelKok yes I think you're correct on further reading. I've changed it. – sprinter Sep 16 '16 at 02:59
  • "' inw' could be the name of a variable but it's not legal syntax to have a variable name in that context "... what would "that context" be? Having an assingment after the 'inw'? When that wouldn't be allowed. – M.Ionut Jan 15 '22 at 15:37