在下面的代码中,没有表达式的return语句的作用是什么

what does the return statement without an expression do as in code below

本文关键字:return 语句 是什么 表达式 作用 代码 在下面      更新时间:2024-09-23

我找不到这个返回语句工作的逻辑原因。尽管我读了很多,它应该返回undefined,但程序会直接将它带到递归调用功能低于

#include <iostream>
using namespace std;
// Recursive function to print the pattern without any extra
// variable
void printPattern(int n)
{
// Base case (When n becomes 0 or negative)
if (n ==0 || n<0)
{
cout << n << " ";
return;
}
// First print decreasing order
cout << n << " ";
printPattern(n-5);
// Then print increasing order
cout << n << " ";
}
// Driver Program
int main()
{
int n = 16;
printPattern(n);
return 0;
}

以上代码的输出是

16 11 6 1-4 1 6 11 16

递归并不是特别的。这又是你的函数,但我隐藏了名称,所以你看不到它是哪个函数。

void XXXXXXXXXX(int n)
{
// Base case (When n becomes 0 or negative)
if (n ==0 || n<0)
{
cout << n << " ";
return;
}
// First print decreasing order
cout << n << " ";
printPattern(n-5);
// Then print increasing order
cout << n << " ";
}

XXXXXXXXXX(-1(做什么?没错:它打印-1

XXXXXXXXXX(16(做什么?没错:它打印16,然后打印11的图案,然后再打印16。

现在你能明白为什么XXXXXXXXXX(16(在开头和结尾打印16吗?

return(无论函数是否递归(将向调用者传递一个可选值,然后在调用者中继续执行。