Recursion 在函数中减少参数是否合法?

Recursion 在函数中减少参数是否合法?,recursion,arguments,Recursion,Arguments,在函数中减少参数是否合法 int Test(int num){ if(num == 0) { return 0; } else { printf("%d,", num); Test (num--); //-- Is this statement is legal ? } } 这是一个有效的例子。请注意,对Test的每个调用都有它自己的num,尽管它们不共享相同的num。这就是为什么这实际上是一样的: int Test(int num){ i

在函数中减少参数是否合法

int Test(int num){
  if(num == 0)
  {
    return 0;
  }
  else
  {
    printf("%d,", num);
    Test (num--);  //-- Is this statement is legal ?
  }
}

这是一个有效的例子。请注意,对
Test
的每个调用都有它自己的
num
,尽管它们不共享相同的
num
。这就是为什么这实际上是一样的:

int Test(int num){
  if(num == 0) {
    return 0;
  }
  else
  {
    printf("%d,", no);
    Test (num - 1);  // Simply subtract one here
  }
}
当使用小于0的数字调用此函数时,您也将得到一个无限循环:

Test(-1) // This loops forever
(我假设这是java代码?)

这是完全合法的,但请注意,它不会影响函数外部的变量-
num
是按值复制到函数中的,因此您只需编辑一个副本。每次调用
Test
时,它都会从调用位置获取当前值
num
的新副本。例如,使用以下代码:

int num = 2;
printf("Num before Test : %d,", num);
int res = Test(num);
printf("Result : %d,", res);
printf("Num after Test : %d,", num);

int Test(int num){
    if(num == 0)
    {
        return 0;
    }
    else
    {
        printf("In Test : %d,", num);
        Test (num--); 
    }
}
产出将是:

Num before Test : 2
In Test : 2
In Test : 1
Result : 0
Num after Test : 2

请注意,
res
可能是您想要的结果,
num
没有改变。

谢谢,我最终使用了(num-1);是的,上面的代码无限次打印相同的数字,导致堆栈溢出。@sasha啊,我错过了-
num++
是“后增量”,这意味着
num
在使用后会增加。因此,使用当前值
num
再次调用Test,然后增加
num
,这是无用的,因为它超出了范围。因此,结果是肯定的,Test只是不断地被调用,并使用相同的
num
值崩溃。使用
num-1
就像前面提到的另一个答案一样有效。很抱歉,我应该意识到我的错误。