Page 243 - Computer_Science_F5
P. 243
Computer Science Syntax errors Program Example 4.4:
A syntax error is a faulty construct that
Syntax error
does not conform to the rules of the
programming language. It is defined as
#include <iostream>
FOR ONLINE READING ONLY
a mistake in the spelling, punctuation or
int main()
order of words in a program. using namespace std;
{
These errors are also called compile- int a = 10;
time errors. They normally happen int b = 15;
when the programmer fails to follow cout << “ “<< (a, b) // semicolon
missed
language syntax rules in the course of return 0;
writing program. Examples of syntax }
errors are misspelling words using a
variable that has not been declared and Error message:
mismatched parentheses or braces, If error: expected ‘;’ before ‘}`
you compile a program that has a syntax
error, the compiler will not run. Instead, Semantic errors
the compiler will tell you at what line a A semantic error is an error that relates
trouble is. Usually, the error can indicate to the meaning of the code, particularly
at the exact line where such a syntax a mistaken idea of how the compiler
error belongs, or the line just before it. interprets the code. Semantic errors are
typically syntactically valid, but they are
In case the problem is incorrectly nested inconsistent in their meaning or invalid
braces, the actual error may be at the such as attempting to divide a number
beginning of the nested block. Once you by zero. Semantic errors happen when
fix the error, and compile it again, the the statements written in the program
program will run successfully. cannot be well interpreted by the
compiler. Sometimes these will cause
The three most frequent syntax errors your program to crash, such as in the
that novice programmers commit include: case of division by zero: Semantic errors
missing parenthesis (}), printing the value are problems with a program that runs
without producing error messages, but it
of a variable without declaring it, and does not do the right thing. For example,
missing semicolon (;). The following an expression may not be evaluated in
C++ program in Program Example 4.4 the order you expect, but yielding an
illustrates syntax errors. incorrect result. The following Program
234
for Advanced Secondary Schools
Computer Science Form 5.indd 234 23/07/2024 12:33

