C语言中条件运算符代码(a>b)? return a : return b; 出现编译错误的原因咨询
(a>b)? return a : return b; Causes a Compile Error in C Hey there! Let's break down exactly why this line of code is throwing a compile error in C.
The Core Misunderstanding
The ternary operator (? :) is an expression, not a drop-in replacement for an if-else statement block. Expressions are code that evaluates to a concrete value, while statements are actions that perform operations (like return, which exits a function and sends back a value). This distinction is key here.
What's Wrong With Your Code?
The syntax rule for the ternary operator is strict:
condition ? expression1 : expression2
Both expression1 and expression2 must be valid expressions that produce a value. But return a and return b are statements—they don't evaluate to a value the way a variable or arithmetic operation does. The compiler sees these and thinks, "Wait, I need a value here, not an action!" which leads to the compile error.
The Correct Ways to Write This Logic
You have two straightforward options to achieve what you're trying to do:
1. Use the ternary operator as part of the return statement
Since the ternary operator outputs a value, you can pass that value directly to return:
return (a > b) ? a : b;
Here, (a > b) ? a : b first calculates the larger of a and b, then return sends that value back from the function—this fits perfectly with C's syntax rules.
2. Use an explicit if-else statement
If you prefer the clearer branch structure, this is equally valid:
if (a > b) { return a; } else { return b; }
Quick Recap
- Ternary operator = expression (must return a value)
return= statement (performs an action, isn't a value)- Mixing them like you did violates C's syntax rules, which triggers the compile error.
内容的提问来源于stack exchange,提问作者Kishan N.S

