Skip to the content of the web site.

Lesson 1.9.1: Syntax and semmantic errors

Syntax errors

The sequence of characters of what is an acceptable C++ program is described by a mathematically defined grammar. This grammar defines exactly what is a valid C++ program. There are simply some sequences of characters that will never make any sense what-so-ever in C++. If you enter such a sequence of characters in C++, the compiler will detect the error and notify you with a compile-time error message. The error messages that C++ will display will often point to the exact problem, as we will see.

Definition: grammar
A logical description of what sequences of characters constitute a valid program in a given programming language; consequently, all other sequences of characters do not define a valid program within the language.

Definition: syntax error
An unexpected sequence of characters that is not comprehensible within the grammar of a programming language.

Examples of syntax errors include:

  • Having an unrecognized operator *+*.
  • Having two non-keyword identifiers juxtaposed.
  • Not having a matching delimiter.
  • Forgetting a semi-colon at the end of a statement.
  • Having a keyword used in an incorrect context; for example, trying to use a keyword as an identifier.

Compile-time semantic errors

It is also possible to have a statement that is syntactically correct, but never-the-less do not allow for the code to compile. For example, the following is syntactically correct, but it makes no sense:

#include 

double sin( double x );

double sin( double x ) {
	return y - y*y*y/6.0 + y*y*y*y*y/120.0;
}

The identifier y appears inside the body of the sin function, but it is not declared.

Similarly, if the operands of an operator are incompatible, or if an argument is not of the appropriate type as described in the function declaration, these would lead to compile-time errors.