4. Semantic Errors

The third type of error is the semantic error. If there is a semantic error in your program, it will run successfully in the sense that the computer will not generate any error messages. However, your program will not do the right thing. It will do something else. Specifically, it will do what you told it to do.

The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing. Semantic errors are also called logic errors since they are usually caused by some fault in the logic of your program.

For example, say you were writing a program to calculate your daily earnings based on your weekly salary. You might write a program like the following:

The result surprises you because you thought you were making at least $100 per day (you work Monday thru Friday). According to this program, though, you are making about $85 per day. The error is a logic one because you divided your weekly pay by 7. It would have been more accurate to divide your weekly pay by 5, since that is how many days a week you are actually working.

Check your understanding