Solution to C compiler error: expected ';' before '}' token
When developing using the C programming language, you often encounter various compilers mistake. One of the common errors is "expected ';' before '}' token". This error usually occurs at the end of a function or conditional statement, meaning the compiler expected to see a semicolon there, but actually got a closing curly brace.
This error is often caused by irregular code writing or improper matching of brackets. Some common situations and corresponding solutions will be given below to help you better solve this compiler error.
When writing C code, we need to add a semicolon at the end of each statement to indicate the end of the statement. If the semicolon is missing, the compiler will prompt an "expected ';' before '}' token" error.
For example, the semicolon on line 6 is missing in the following code:
#include <iostream> int main() { int a = 1; int b = 2; if (a < b) { std::cout << "a小于b" << std::endl; } else { std::cout << "a大于等于b" << std::endl; } // 此处缺少分号 return 0; }
The solution is simple, just add it where the semicolon is missing:
if (a < b) { std::cout << "a小于b" << std::endl; } else { std::cout << "a大于等于b" << std::endl; }; // 添加分号
Another common reason is that the brackets in the code are not matched correctly, causing the compiler to not correctly parse the code syntax. In this case, the compiler will prompt an "expected ';' before '}' token" error.
For example, in the following code, the left bracket is missing in the if statement:
#include <iostream> int main() { int a = 1; int b = 2; if a < b) { std::cout << "a小于b" << std::endl; } else { std::cout << "a大于等于b" << std::endl; } return 0; }
The solution is to add the missing left bracket:
if (a < b) { std::cout << "a小于b" << std::endl; } else { std::cout << "a大于等于b" << std::endl; }
Sometimes, we add one or more right curly brackets unnecessarily in the code, causing compiler errors. In this case, the compiler will prompt an "expected ';' before '}' token" error.
For example, in the following code, there is an extra right curly brace on line 9:
#include <iostream> int main() { int a = 1; int b = 2; if (a < b) { std::cout << "a小于b" << std::endl; } else { std::cout << "a大于等于b" << std::endl; }} // 多余的右花括号 return 0; }
The solution is to delete the extra right curly brace:
if (a < b) { std::cout << "a小于b" << std::endl; } else { std::cout << "a大于等于b" << std::endl; } // 删除多余的右花括号
Summary :
When writing C code, you often encounter compiler errors. One of the common errors is "expected ';' before '}' token". We can fix this by checking for missing semicolons, matching parentheses, and extraneous right curly braces. Hope this article can help you better understand and solve this compiler error.
The above is the detailed content of Resolving C++ compiler error: expected ';' before '}' token. For more information, please follow other related articles on the PHP Chinese website!