retagged by
822 views
9 votes
9 votes
Q) For each of the following C statements state whether they contain lexical error, syntax error, semantic error or no error(along with reason) -

i) inta radius =5;

ii) x=127b + z;

iii) printf("%d=%d\n", x);

iv) int p[10]; x=25 + p;
retagged by

2 Answers

Best answer
11 votes
11 votes

i) inta radius =5;

5 valid tokens, 2 matching to identifier, one to constant, 1 to operator and 1 to punctuator.

https://docs.microsoft.com/en-us/cpp/c-language/punctuation-and-special-characters

But this generates a syntax error as two identifiers cannot come together without some other token in between.

ii) x=127b + z;

127b -- causes lexical error as it won't match an identifier which is required to begin with a letter. Also 'b' suffix can be used only for numbers having 0 and 1 -- this also works only in GNU C and not with standard C.

iii) printf("%d=%d\n", x);

7 tokens - printf and x being identifiers, "%d=%d\n" being a string literal, {(, , ,)} being operators and ; being the punctuator. There is no syntax error here and providedx is a declared variable there is no semantic error also.

iv) int p[10]; x=25 + p;

Well, there is no error here, provided these statements are inside some function and x is a pointer to integer type. x = 25+p, returns the address of the 26th element from the start of p --. address of p[25]. The second statement generates a semantic error if given as a global statement -- because 25 + p cannot be done at compile time (as value of p is not known) and global variables are initialized at compile time.

selected by
1 votes
1 votes
If we are able to draw the finite automata for the string then only we can say that the string/token is valid.In i) case we cannot draw the automata that accepts inta.Hence it is lexical error.

A string is said to be grammatically correct if we are able to generate parse tree for it. In ii) we cannot draw the parse tree more precisely we cannot draw the grammar for it. So ii) is syntax error

There is nothing wrong to iii) the output would be value of x followed by = followed by some garbage value.

 

In iv) x=25 + p; means x=25 + base address of p.There is no meaning in doing this so it is semantic error.

Related questions

1 votes
1 votes
2 answers
1
Souvik33 asked Jan 12, 2023
587 views
What is the earliest stage compiler error for the following C code snippet:int x = @33;Lexical ErrorSyntax ErrorSemantic ErrorNone
0 votes
0 votes
2 answers
2
Mohit Aggarwal asked Dec 1, 2021
1,391 views
what is the difference between lexical error and syntax error?
0 votes
0 votes
3 answers
3
VJ2793 asked Feb 12, 2019
670 views
fro(int I=0; I <5;I++);what kind of compilation error is this ?
6 votes
6 votes
7 answers
4
Na462 asked Oct 5, 2018
3,484 views