Home >Backend Development >C++ >C++ syntax error: The statement is missing a semicolon, how to correct it?

C++ syntax error: The statement is missing a semicolon, how to correct it?

PHPz
PHPzOriginal
2023-08-22 09:57:292827browse

C is a very powerful programming language, but when writing code, you will inevitably encounter syntax errors. Among them, missing semicolons in statements is one of the common errors. In this article, we will discuss the situation when a statement is missing a semicolon and provide solutions.

What is a statement missing a semicolon?

In C programs, each statement usually ends with a semicolon (;). The semicolon tells the compiler that the current statement has reached the end. If you forget to add a semicolon at the end of a statement, the compiler will report a syntax error.

For example, the following code will cause a syntax error:

#include <iostream>
using namespace std;

int main()
{
  cout << "Hello World!" << endl   // 遗漏分号
  return 0;
}

The compiler will return the following error message:

error: expected ';' before 'return'
return 0;
^~~~~~

This is because the compiler cannot Determine the end of the code. In this case, the compiler defaults to treating the entire line of code as one statement until it encounters the next statement or the end of the block of code.

How to correct the error of missing semicolon in the statement?

To correct the error of a statement missing a semicolon, you need to find the statement that is missing a semicolon and add a semicolon at the end.

In the above example, we should add a semicolon at the end of the statement as follows:

#include <iostream>
using namespace std;

int main()
{
  cout << "Hello World!" << endl;   // 在语句末尾添加分号
  return 0;
}

Remember, in a C program, every statement should end with a semicolon (; )Finish. If you add parentheses, quotes, or other characters to your statement, don't forget to add a semicolon at the end. Otherwise the compiler will think you haven't finished writing the statement.

Summary

Missing semicolon in a statement is one of the most common mistakes in C programming. This error usually occurs because programmers are careless while writing code. To avoid this error, it is recommended to follow some rules while writing code, such as ending every statement with a semicolon. Don't panic if you encounter this error, just double-check your code and add semicolons at the end of the statements that are missing them.

The above is the detailed content of C++ syntax error: The statement is missing a semicolon, how to correct it?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn