Re: ? : Operator

From: marbac (marbac_at_chello.at)
Date: 03/24/05


Date: Thu, 24 Mar 2005 07:42:16 GMT

OJ schrieb:
> Hi,
> as a newbie, could someone explain the "? :" operator to me...
> I wrote this as part of a small routine to fill an array with the first
> 20 items of the Fibonacci sequence, but it produces strange results...
>
> int arrFib[20];
> int i,k;
>
> for(i=0;i<20;i++);
> {(i<2 ? arrFib[i] = 1 : arrFib[i] =(arrFib[i-1] + arrFib[i-2]));}
>

That is the conditional expression operator. It behaves like
if (i<2) arrFib[i] = 1; else arrFib[i] =(arrFib[i-1] + arrFib[i-2]);

with the difference, that it also returns the value.

I often use it to decide for a value within an operation chain

e.g.:

for (1=0;i<20;i++)
arrFib[i]=(i<2)?1:(arrFib[i-1]+arrFib[i-2]); // gives the same result.

regards marbac



Relevant Pages

  • Re: why cant functions return arrays
    ... int f; ... the hypothethical return array is created. ... "under" the stack frame for the called routine. ... as after the call those automatic variables ...
    (comp.lang.c)
  • Re: why cant functions return arrays
    ... int f; ... for such a language restricton. ... Where would the array get temporarily stored? ... "under" the stack frame for the called routine. ...
    (comp.lang.c)
  • Re: ? : Operator
    ... > I wrote this as part of a small routine to fill an array with the first ... > int i,k; ... where the parentheses are in fact optional. ...
    (comp.lang.cpp)
  • ? : Operator
    ... as a newbie, ... I wrote this as part of a small routine to fill an array with the first ... int i,k; ...
    (comp.lang.cpp)