[英]Why does --x; work and x— gives seg fault in recursion code
This code gives me a seg fault, but when I change the x--
to --x
it prints correctly. 这段代码给了我一个seg错误,但当我将
x--
更改为--x
它会正确打印。
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 --x
is whether the returned value is before or after the decrement. x--
和--x
之间的区别在于返回值是在减量之前还是之后。
In myFunc(x--)
, x--
returns the old value. 在
myFunc(x--)
, x--
返回旧值。 So myFunc()
gets called repeatability with the same value -> infinite recursion. 所以
myFunc()
被称为可重复性,具有相同的值 - >无限递归。
In myFunc(--x)
, --x
returns the new value. 在
myFunc(--x)
--x
返回新值。 So myFunc()
gets called with a decreasing number each time -> no infinite recursion. 所以
myFunc()
每次调用的次数递减 - >无无限递归。
It will be easier to see this if you moved your printf
to the start of the function call: 如果将
printf
移动到函数调用的开头,将会更容易看到这个:
void myFunc (int x) {
printf("%d, ", x);
if (x > 0) {
myFunc(x--);
}
else
return;
}
Output: (when called with 10) 输出:(用10调用时)
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, ...
The post-decrement operation ( x--
) takes place after the argument is evaluated, so myFunc
is repeatedly called with the same value. 后递减操作(
x--
) 在求值参数后发生,因此使用相同的值重复调用myFunc
。 The pre-decrement ( --x
) operation takes place before the argument is evaluated, which works as expected. 预递减(
--x
)操作在评估参数之前发生,它按预期工作。
Because the modification of -- is either post or pre. 因为 - 的修改是post或pre。 When you call x-- it is post, and therefore runs after myFunc is called, in this case doing nothing.
当你调用x--时它是post,因此在调用myFunc之后运行,在这种情况下什么都不做。 --x will be called before myFunc and therefore will affect x.
--x将在myFunc之前调用,因此会影响x。
x-- decrements the variable after the use. x--在使用后递减变量。 This is the reason why you pass to your function always the same value, that should be decreased, but doesn't, as well as the function repeats itself.
这就是为什么你传递给你的函数总是相同的值,应该减少,但不是,以及函数重复自己。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.