Re: Return statement twice in the same expression



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).

.



Relevant Pages

  • Re: C Standard Regarding Null Pointer Dereferencing
    ... void foo{ ... int main{ ... Does evaluation of the cast operator on line 08 yield a defined result ...
    (comp.lang.c)
  • Re: INT() vs CInt()
    ... >> will yield different results. ... CInt and Int are not different names for similar functions. ... > mathematical truncating function. ... "conversion function that also rounds while converting." ...
    (microsoft.public.vb.general.discussion)
  • Re: Plauger, size_t and ptrdiff_t
    ... Plauger's "The Standard C Library," where he states "... ... This language would not rule out one being int ... operator can only yield values from 0 to 65535, ...
    (comp.lang.c)
  • Re: double cast to int reliable?
    ... converting then to int, will not give you the original. ... that "most" integers yield a slightly smaller double when converted ... to a floating-point type to yield an exact result when that result ... converting the value 1 from int to double and back ...
    (comp.lang.c)
  • Re: Why no compilation error.
    ... but i get the compilation error if i initialize the variable "a" in a.c ... int a = 10. ... as correct or incorrect as anything else. ...
    (comp.lang.c)