Willturner Willturner - 26 days ago 12
C Question

Does the given C code has both syntax error and semantic error?

Already, so many downvotes for this question. Is anyone reading it carefully, I didn't applied comma intentionally.

#include<stdio.h>

int main()

{

aloft a b ; // I have not applied comma intentionally

a = 4.00 ; b = 20.00;

printf("%d %d",a,b);

return 0;

}


I ran the above program and I got the following output:

prog.c: In function 'main':
prog.c:7:7: error: unknown type name 'aloft'
aloft a b ;
^
prog.c:7:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'b'
aloft a b ;
^
prog.c:9:7: error: 'a' undeclared (first use in this function)
a = 4.00 ; b = 20.00;
^
prog.c:9:7: note: each undeclared identifier is reported only once for each function it appears in
prog.c:9:18: error: 'b' undeclared (first use in this function)
a = 4.00 ; b = 20.00;
^


Clearly, a and b are undeclared as shown in the output, so it gives clear information that there is a semantic error.

But, I am not having a clear idea that is it syntax error or not ?

As the code suffers from the following output :

expected '=', ',', ';', 'asm' or '__attribute__' before 'b'


This shows that syntax is not properly encoded in the program. Does this means syntax error?

Alternatively, I tried to run this program as:

#include<stdio.h>

int main()

{
typedef float aloft;

aloft a b ;

a = 4.00 ; b = 20.00;

printf("%d %d",a,b);

return 0;

}


But still the output shows B undeclared and no use of comma, ;, etc.

prog.c: In function 'main':
prog.c:8:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'b'
aloft a b ;
^
prog.c:8:15: error: 'b' undeclared (first use in this function)
prog.c:8:15: note: each undeclared identifier is reported only once for each function it appears in
prog.c:10:7: error: 'a' undeclared (first use in this function)
a = 4.00 ; b = 20.00;
^


It is clear that semantic error is there. But, Is there syntax error ? If not, then how it passes the syntax analysis phase ?

Answer

There are both syntax and semantic errors.

The syntax error is missing comma between a and b.

The semantic error is wrong type name (aloft instead of float) for a and b variables.

The reason why you see both syntax and semantic errors is that compiler does the best job in order to recover and provide as much output as possible. Even though it might be misleading and produces lot more than it's really necessary to fix the root cause, in many cases it may help and avoids many runs of compiler to fix the issues sequentially.

Comments