-2

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);
}
unwind
  • 391,730
  • 64
  • 469
  • 606
suyol854
  • 123
  • 3

1 Answers1

4

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.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305