Reputation: 689
I am examining errors in different C programs and differentiating between them.
Currently, I am confused what type of error is there in this code.
#include <stdio.h>
int main(void) {
in/*hello*/z;
double/*world*/y;
printf("hello world");
return 0;
}
When i run this program, i get compilation error as :
prog.c: In function 'main':
prog.c:4:5: error: unknown type name 'in'
in/*this is an example*/z;
^
prog.c:5:30: warning: unused variable 'y' [-Wunused-variable]
double/*is it an error?*/y;
^
prog.c:4:29: warning: unused variable 'z' [-Wunused-variable]
in/*this is an example*/z;
^
I know that warning will not prevent from compiling, but there is an error
error: unknown type name 'in'
So, Is this syntax or semantic error ?
Upvotes: 0
Views: 570
Reputation: 6298
I think it is typical typo:
in/*hello*/z;
and you wanted int
type for your variable z
:
int /*hello*/ z;
Upvotes: 0
Reputation: 51
There is obviously a syntax error. First of all we have to clarify a thing: you have to understand clearly what's the difference between syntax and semantics. Syntax are the "grammar rules" of a programming language, when the compiler does not compile, you've done syntax errors. When you do a semantics error you have done a code that compiles successfully, but, when executed does things you do not want to. C is a strong-typed language: this means that you have to declare variables before using them. You have done a couple of errors, but don't worry, let's analyze them together. First error: you used a type of variable not possible: and the compiler simply showed it up. For the "in" type i'm assuming that you meant int, but when you code you have constantly to ask yourself: "Is this variable useful now?" The answer to this question is: "No", because you just want to make an output. So the correct implementation of this simple procedure is:
http://groups.engin.umd.umich.edu/CIS/course.des/cis400/c/hworld.html
Hope that this helps.
Bye.
Gerald
Upvotes: 1
Reputation: 2590
The code does not compile, so this is a syntax error.
A syntax error is when the code is not valid at all, and cannot be compiled. Such as trying to declare a variable of a type that does not exist (as in your snippet), or performing an invalid assignment, or many other things.
5 = a;
That is a syntax error because you cannot assign a value to a number.
int if;
That is a syntax error because if
is a keyword that cannot be a variable name.
A semantic error is code that is valid and compiles but does not do what you would like. Consider the following simple function to square a number:
int square (int value)
{
return value ^ 2;
}
That function does not square the number passed to it but rather performs a bitwise XOR. Yet, in some other languages, ^ 2
would be the syntax to square a number, so this is a semantic error that could conceivably exist in C code.
Upvotes: 0