I would like you to explain this function to me, I do not understand this syntax:
double sum_arithmetic(double x0, double r, int n)
{
return n == 0 ? 0 : x0 + sum_arithmetic(x0 + r, r, n-1);
}
I would like you to explain this function to me, I do not understand this syntax:
double sum_arithmetic(double x0, double r, int n)
{
return n == 0 ? 0 : x0 + sum_arithmetic(x0 + r, r, n-1);
}
The ternary operator resembles a if
but is an expression and not a statement . So you can use anywhere you accept an expression, as long as your results are also expressions. I actually prefer to call it conditional, since ternary is circumstantial and does not define what it does.
It is composed of three parts (so it is called erroneously ternary operator):
if
, equal to any condition), in its n == 0
example. x0 + sum_arithmetic(x0 + r, r, n-1)
. Always only one of them will be considered.
Then you will read this as follows:
If n
is equal to zero, consider as result zero, otherwise make the following calculation x0 + sum_arithmetic(x0 + r, r, n-1)
and consider the result of it.
Your code could be written with if
this way:
if (n == 0) {
return 0;
} else {
return x0 + sum_arithmetic(x0 + r, r, n-1);
}
The correct name should be a conditional operator, but since it is the only ternary operator known in mainstream languages, it eventually gets its name.
Some additional information in that answer and this and at Wikipedia >.
It is a concept where a function calls itself and, in general, it has a condition where it is no longer necessary to call it (this is not mandatory but if it does not have an output form, the calls will be infinite and you will end up with a stack overflow error.
It has a joke that helps to understand a little:
To understand recursion, you need to understand what recursion is. Got it?
Now search Google for the word recursion
. You'll find another joke.
A classic example of recursion is the factorial calculation:
To learn more, see in this answer and #
As long as the third parameter n
is not zero, it will compute the sum of x0
with the result of the sum_arithmetic
function itself, passing as parameters the first parameter x0
added to the second parameter r
, then it will pass the r
itself and finally passes to the last parameter the n
received subtracted from one. As with every call the n
is always reduced from one, one hour will arrive at zero and then it will simply return zero according to the ternary operator, and will no longer call the function.
If you have a very large number of recursive calls of the sum_arithimetic
function, you may have a stack overflow for filling all the memory reserved for the stack your application.