I found this piece of code and I am trying to figure out how it works, but I don't understand the part after the return statement. Can somebody explain this?
int f(int y)
{
return (y<=1)?1:y*f(y-1);
}
I found this piece of code and I am trying to figure out how it works, but I don't understand the part after the return statement. Can somebody explain this?
int f(int y)
{
return (y<=1)?1:y*f(y-1);
}
This:
int f(int y)
{
return (y<=1) ? 1 : y*f(y-1);
}
is equivalent to this:
int f(int y)
{
if(y <= 1)
{
return 1;
} else
{
return y*f(y-1);
}
}
which should be clear to you by now, that it's a recursive function that uses The ternary (conditional) operator in C.
The ternary operator has this general form:
condition ? a : b
where if condition
evaluates into True, then a
will be executed, else b
.