Home >Backend Development >C++ >How to solve C++ syntax error: 'expected declaration before '&' token'?
How to solve C syntax error: 'expected declaration before '&' token'?
When learning and writing C programs, we often encounter various errors. One of them is the 'expected declaration before '&' token' error. This article will introduce the cause and solution of this error, and provide corresponding code examples.
Cause of error:
In C, the 'expected declaration before '&' token' error is usually caused by an incorrect reference (&) symbol during a function call or definition. This error often occurs in the parameter list of a function declaration or function definition. Here is a sample code:
#include<iostream> void foo(int &a, int &b) { // function body std::cout << "Sum: " << a + b << std::endl; } int main() { int num1 = 10; int num2 = 20; foo(num1, num2); // 函数调用 return 0; }
Solution:
To resolve this error, we need to confirm that the parameters match between the function call and the function declaration/definition.
Fix example:
void foo(int &a, int &b) { // 声明/定义中的参数类型需要与函数调用中的参数类型一致 // function body std::cout << "Sum: " << a + b << std::endl; }
Fixing example:
foo(num1, num2); // 函数调用时的参数需要与函数声明/定义中的参数一致
With the above fixing example, we can solve the 'expected declaration before '&' token' error.
It is worth noting that this article only provides a common situation that causes this error. In actual situations, there may be other causes of this error. This error is one of the common syntax errors during programming and can be confusing for beginners, but it is easily fixed by carefully checking the code and paying attention to parameter matching.
Summary:
In C programming, the 'expected declaration before '&' token' error is usually related to the use of reference symbols, especially in parameter lists in function calls and declarations/definitions. To resolve this error, we should carefully check that the parameter types and order are consistent in the function call and function declaration/definition. By fixing the parameter matching error, we can easily resolve this error and make the program run smoothly. When writing C code, it is very common to encounter errors. For beginners, it just requires patience and care. We can gradually become familiar with and master the methods of fixing these errors.
The above is the detailed content of How to solve C++ syntax error: 'expected declaration before '&' token'?. For more information, please follow other related articles on the PHP Chinese website!