This code gives me a seg fault, but when I change the x-- to --x it prints correctly.
Are not they the same????
int main()
{
myFunc(5);
return 0;
}
void myFunc (int x) {
if (x > 0) {
myFunc(x--);
printf("%d, ", x);
}
else
return;
}
No they are not the same.
The difference between
x--and--xis whether the returned value is before or after the decrement.In
myFunc(x--),x--returns the old value. SomyFunc()gets called repeatability with the same value -> infinite recursion.In
myFunc(--x),--xreturns the new value. SomyFunc()gets called with a decreasing number each time -> no infinite recursion.It will be easier to see this if you moved your
printfto the start of the function call:Output: (when called with 10)