Programming errors a compiler will detect in C++
By: Stanley B.
Part of the compiler's job is to look for errors in the program text. A compiler cannot detect whether the meaning of a program is correct, but it can detect errors in the form of the program. The following are the most common kinds of errors a compiler will detect.
Syntax errors. The programmer has made a grammatical error in the C++ language. The following program illustrates common syntax errors; each comment describes the error on the following line:
// error: missing ')' in parameter list for main
int main ( {
// error: used colon, not a semicolon after endl
std::cout << "Read each file." << std::endl:
// error: missing quotes around string literal
std::cout << Update master. << std::endl;
// ok: no errors on this line
std::cout << "Write new master." <<std::endl;
// error: missing ';' on return statement
return 0
}
Type errors. Each item of data in C++ has an associated type. The value 10, for example, is an integer. The word "hello" surrounded by double quotation marks is a string literal. One example of a type error is passing a string literal to a function that expects an integer argument.
Declaration errors. Every name used in a C++ program must be declared before it is used. Failure to declare a name usually results in an error message. The two most common declaration errors are to forget to use std:: when accessing a name from the library or to inadvertently misspell the name of an identifier:
#include <iostream>
int main()
{
int v1, v2;
std::cin >> v >> v2; // error: uses " v "not" v1"
// cout not defined, should be std::cout
cout << v1 + v2 << std::endl;
return 0;
}
An error message contains a line number and a brief description of what the compiler believes we have done wrong. It is a good practice to correct errors in the sequence they are reported. Often a single error can have a cascading effect and cause a compiler to report more errors than actually are present. It is also a good idea to recompile the code after each fixor after making at most a small number of obvious fixes. This cycle is known as edit-compile-debug.
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++