[英]return statement in Recursion: C++
我正在嘗試實現二進制搜索樹,並試圖實現從節點搜索值。 本書通過遞歸實現了它。
為了更好地理解該過程,我嘗試將邏輯應用於數組。
考慮下面的代碼:
#include <iostream>
#include "BST.h"
using namespace std;
char Array[]={'A','B','C','D','E','F','G','H','I','J'};
char fn(int i,int x)
{
if( i == x)
{
cout << "Case : 1 " << endl;
return Array[x];
}
else if( i > x)
{
cout << "Case : 2 " << endl;
fn(--i,x);
}
else if(i < x)
{
cout << "Case : 3 " << endl;
fn(++i,x);
}
}
int main()
{
cout << fn(2,7) << endl ;
system("Pause");
return 0;
}
我想要實現的是fn(int i,int x): from index i , search index x and return the value at index x
。
The output is:
Case : 3
Case : 3
Case : 3
Case : 3
Case : 3
Case : 1
H
Press any key to continue . . .
遞歸邏輯工作正常。 但是在編譯時,它將警告顯示為main.cpp(28): warning C4715: 'fn' : not all control paths return a value
因此,如果我將代碼修改為:
char fn(int i,int x)
{
if( i == x)
{
cout << "Case : 1 " << endl;
return Array[x];
}
else if( i > x)
{
cout << "Case : 2 " << endl;
return fn(--i,x);//added return here
}
else if(i < x)
{
cout << "Case : 3 " << endl;
return fn(++i,x);//added return here
}
}
沒有編譯警告,輸出完全相同。 我的問題是what purpose does return in each 'else if test condition' serve, I am returning from my base condition ie return Array[x]; and this is what I wanted my function to return. Why to put return in all the test conditions?
是what purpose does return in each 'else if test condition' serve, I am returning from my base condition ie return Array[x]; and this is what I wanted my function to return. Why to put return in all the test conditions?
what purpose does return in each 'else if test condition' serve, I am returning from my base condition ie return Array[x]; and this is what I wanted my function to return. Why to put return in all the test conditions?
編輯剛意識到,函數的第二個版本仍在發出編譯警告main.cpp(30): warning C4715: 'fn' : not all control paths return a value
應該怎么辦? 怎么解決?
我的問題是每次“其他情況下”服務返回的目的是什么,我是從基本條件返回的,即return Array [x]; 這就是我想要函數返回的內容。 為什么要在所有測試條件下退貨?
這會將值從基本情況最終返回到遞歸調用的頂層。
為了更好地理解這一點,請記住return
只是將執行返回給名為fn()
的函數。 遞歸調用fn()
,調用方和被調用方都是fn()
函數的副本。 您可以多次遞歸調用fn()
,並且每次遞歸調用都必須將結果返回給其父級,並最終返回到最初稱為fn()
的函數。
我建議您拿一張紙和一支鉛筆,並通過示例輸入手動進行操作。 跟蹤fn()
每個遞歸調用,以及從每個遞歸返回時會發生什么。 手動執行此操作后,請使用調試器逐步檢查代碼,以確保其按預期的方式工作。
如果沒有return
之前fn(--i, x)
和fn(++i, x)
該函數不從這些語句返回。 它嘗試運行該功能可能具有的任何其他語句。 但是,沒有任何東西。 它到達函數的末尾而沒有遇到return
語句。
返回類型不是void
函數必須具有有效的return
語句。 否則,代碼的行為是不確定的。 您可以在https://stackoverflow.com/a/1610454/434551上了解有關此內容的更多信息。
編譯器通過報告警告來幫助您避免該問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.