看板 C_and_CPP 關於我們 聯絡資訊
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 ) ( 未必需要依照此格式,文章條理清楚即可 ) 遇到的問題: (題意請描述清楚) #include <stdio.h> int foo(int a) { if( a == 0 ) return a; else if( a > 0 ) foo(--a); else foo((a+2)*3); } void main(void) { printf("result: %d\n", foo(5)); } 必須讓編譯器清楚看到某一行的開頭是return,否則它會出 現warning,如下: 'foo' : not all control paths return a value test.obj - 0 error(s), 1 warning(s) 希望得到的正確結果: compile不要出現警告,如下所示: test.obj - 0 error(s), 0 warning(s) 程式跑出來的錯誤結果: 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) VC6++ 有問題的code: (請善用置底文標色功能) 補充說明: 我的 foo 有「邏輯錯誤」,這個我知道。因 為臨時隨手寫的,目地只想表達這個架構。 我在寫遞迴程式時,常會遇到這個問題。 而遞迴程式,就是要用if去判斷,再return 我要問的不是foo有邏輯錯誤,而是要問 int foo(xxxxx) { if( xxx ) return else if( xxx ) foo( xxx ); else foo( xxx ); } 這樣子的架構compile不行? 註:1.因為要寫遞迴,所以return不得已一定要包在if裡面。 2.compile 是:0 error(s), 1 warning(s) build 是:0 error(s), 0 warning(s) 非得要這樣子compile才會閉嘴 inf foo(xxx) { xxx xxx xxx return; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 211.76.74.145
loveme00835:寫出遞迴式, 有等號的地方就是需要return, 這也算是 10/14 08:52
loveme00835:邏輯錯誤... 10/14 08:53
purpose:改成 void foo(int a) 拿掉 return 不就好了 10/14 09:06
purpose:你總不會說,因為要寫遞迴,所以非得用到return吧 10/14 09:07
TsinTa:把foo(--a)和foo((a+2)*3)前面都加上return 10/14 09:28
suhorng:因為你的程式執行到else if或else的時候沒有回傳值 10/16 11:34
suhorng:當然在某些情況下可能運氣好會得到正確回傳值... 10/16 11:34