How to solve C syntax error: 'expected primary-expression before ':' token'?
In C programming, syntax errors are a common problem. One of the common errors is the "expected primary-expression before ':' token" error message. This error usually occurs when using conditional expressions and the ternary operator. This article will introduce the cause of this error and give the corresponding solution.
First, let’s look at a simple code example:
int main() { int x = 5; int y = 10; int max = (x > y) ? x : y; return 0; }
In the above code, we try to use conditional expressions and ternary operators to compare the sizes of x and y, and compare the The larger value is assigned to the variable max. However, the compiler reported an error "expected primary-expression before ':' token". This is because in C syntax, the "?" and ":" in the ternary operator must be replaced by expressions. When the expression after the question mark is true, the expression after the colon will be executed; otherwise, the expression before the colon will be executed.
To resolve this error, we need to ensure that the conditional expression used in the ternary operator is a legal expression. Common reasons for this error include the following:
int main() { int x = 5; int y = 10; int max = (x >) ? x : y; // 错误:条件表达式缺失 return 0; }
int main() { int x = 5; int y = 10; int max = x > y ? x : y; // 错误:缺少条件表达式的括号 return 0; }
In order to solve the error in the above two cases, we only need to use a legal expression in the position of the conditional expression and make sure to use the correct grammar.
Also, when we use the ternary operator, we also need to ensure that the correct syntax is used in its syntax context. For example, in the following code, we try to assign the result of a ternary operator to an illegal expression, resulting in an error:
int main() { int x = 5; int y = 10; (x > y) ? x : y = max; // 错误:赋值给非法的表达式 return 0; }
To solve this error, we need to make sure that we are using the ternary operator , assign the result to a legal expression, such as a variable.
To sum up, when the C syntax error "expected primary-expression before ':' token" occurs, we should check the following aspects:
By paying attention to these details, we can avoid this common C syntax error and make our code more stable and reliable.
The above is the detailed content of How to solve C++ syntax error: 'expected primary-expression before ':' token'?. For more information, please follow other related articles on the PHP Chinese website!