Re: Return statement twice in the same expression
- From: "Antonio Contreras" <anconor@xxxxxxxxx>
- Date: 21 Sep 2005 14:27:01 -0700
Nerox wrote:
> Hi, If i write:
>
> #include <stdio.h>
>
> int foo(int);
>
> int main(void){
> int a = 3;
> foo(a);
> }
>
> int foo(int n){
> n > 10 ? return 1 : return 0;
> }
>
> This code yields a compilation error, but if i write:
>
> return n > 10 ? 1 : 0;
>
> instead, it works. Why?
> What does the standard say about that?
>
The ternary operator (<expr1> ? <expr2> : <expr3>) is an operator, not
a control structure. [1]
All expressions involved in the ternary operator must yield a value.
The statement "Return x" does not yield a value, in fact it returns
control to the caller function, so there is no one to return a value
to. That's the reason why "n > 10 ? return 1 : return 0" gives
compilation errors.
return n > 10 ? 1 : 0, OTH is perfectly legal. The ternary operator
yields a value that is passed to return.
BTW, in your code it would be totally equivalent, and much cleaner to
simply write:
return n > 10;
[1] It can be used as a control structure. A sentence like:
n > 10 ? a = 1 : a = 0;
would be perfectly legal, but is bad practice. The reason why this is
legal is because an assigment does yield a value (the value being
assigned).
.
- Follow-Ups:
- Prev by Date: Re: Return statement twice in the same expression
- Next by Date: Re: Why this function doesent work correctly...??
- Previous by thread: Re: Return statement twice in the same expression
- Next by thread: Re: Return statement twice in the same expression
- Index(es):
Relevant Pages
|