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.

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

6 Comments

@Sprinter Shouldn't the first line be a semantic error? tutorialspoint.com/compiler_design/…
that's what was confusing me since I had read something similar before.
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.
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.
@SamuelKok yes I think you're correct on further reading. I've changed it.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.