在递归中使用 post-increment

Use of post-increment in recursion

我是这个社区的新手,我试图理解为什么这个递归函数没有堆栈溢出,当我在函数调用中使用 post 增量 (c++) 时,这传递了一个值 0(我在调试时看到了),但是当调用下一个函数时,它的值为 1。 我不明白何时应用 post 增量,以及为什么如果我将 0 的值传递给函数,在第一个参数中执行 s+1;

#include <stdio.h>
#include <string.h>
#define LARGO 20

char *esta (char s[], int c){
 if(strlen(s))
    printf("\n %s", esta(s+c,c++));
 return s;
}

int main()
{
 char cad[LARGO]= {"hello"};
 int c=0;
 printf("\n %s", esta(cad,c++));
}

P.S。 : 对不起,如果我的英语不是最好的,那不是我的主要语言,我会尽力解释;如果有不清楚的地方告诉我,我会改。

参数的计算顺序未定义,因此编译器可以选择它想要的任何顺序。在您的情况下,它首先将 c++ 评估为 0,然后 s+c 评估为 s+1.

参见维基百科Sequence point。特别是第 4 项给出了完整的解释:

A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed.

  1. Before a function is entered in a function call. The order in which the arguments are evaluated is not specified, but this sequence point means that all of their side effects are complete before the function is entered. In the expression f(i++) + g(j++) + h(k++), f is called with a parameter of the original value of i, but i is incremented before entering the body of f.

换句话说:编译器被指派在这里做一项艰巨的工作。它必须传递 before POST-increment 的原始值(因为这是 POST-increment 的工作方式) 并同时在进入函数 esta 之前执行所有副作用。这些副作用之一是增加 c 的值。而且,由于未指定评估参数的顺序,因此您的编译器会先评估c++,然后再评估s+c,在这种情况下表示 s+1。因此,当您退出递归并在每次迭代中打印字符串余数时,您的行越来越短,最终 strlen(s)==0