![](/img/trans.png)
[英]Carboard.c:12:1: warning: control reaches end of non-void function [-Wreturn-type]
[英]warning: control reaches end of non-void function [-Wreturn-type]
我得到了一段代碼,這樣:
int check(int d, char arr[9][9], int rep_arr[45][3]) {
int p = findProb(d, arr, rep_arr, 0) ;
if (isIdeal(d, arr) == 1) {
print_array(d,arr) ;
return 1 ;
}
else if(isIdeal(d,arr) == 0 && p == 0){
printf("Fail\n") ;
return 0 ;
}
else if (isIdeal(d, arr) == 0 && p != 0) {
#do something recursively..
}
其中isIdeal(d, arr)
只能等於0
或1
而p
可以等於0
或其他整數。 但是,編譯器給了我標題中給出的錯誤。
后來我在那段代碼的末尾添加了return 0
。
現在它可以工作,但不能以功能方式工作,因為函數返回的內容非常重要。
另一件重要的事情是,當我添加一個else
塊以避免在該站點上的另一個主題中指示的失敗時, 請參閱更多鏈接,它從未進入該else
塊。但是,無論是否添加else
塊,它始終return 0
,通過哪種方式所有的可能性都以return
線結束。 如何 ?
如果您確定可能的值,那么您可以將整個函數替換為:
int foo(int case1, int case2) {
if (case1 == 1) {
return val;
}
return case2 == 0 ? val2 : val3;
}
並同時使您的警告靜音。
如果您擔心case1
可能不是1
或0
,那么只需更改為:
int foo(int case1, int case2) {
assert(case1 == 0 || case1 == 1);
if (case1 == 1) {
return val;
}
return case2 == 0 ? val2 : val3;
}
編譯器不知道的價值觀是什么case1
和case2
的參數會。 您的if
條件不處理這些參數可能包含的所有可能值(忽略您可能只傳入 1 和 0)。 因此,編譯器會正確警告您可以在不返回任何內容的情況下到達函數的末尾。
如果您真的確定這永遠不會發生,請將其轉換為運行時錯誤並在函數末尾放置一個斷言(您可能仍需要在斷言后返回以消除警告,我不確定)。
int foo(case1, case2) {
// your if conditions here
assert(0);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.