[英]What (actually) happens, when a function with the warning "control reaches end of non-void function" is called?
[英]“warning: control reaches end of non-void function” but actually the function is declared as int and return an int
我有這個功能:
int firstHeapArray (IntHeapArray h) {
if(!emptyHeapArray(h))
return h.array[0];
}
它被聲明為int,這是IntHeapArray結構:
typedef struct intHeapArray {
int *array;
int size;
} IntHeapArray;
您能說為什么我在編譯時收到此警告嗎?
heap-test.c: In function ‘firstHeapArray’:
heap.h:31:1: warning: control reaches end of non-void function
非常感謝你。
錯誤消息指出您擁有的方法不是void
返回值,但是您到達末尾卻沒有返回值。 您需要返回一個有效的int值。
問題在這里:
int firstHeapArray (IntHeapArray h) {
if(!emptyHeapArray(h))
return h.array[0];
// If emptyHeapArray(h) is true, you reach here...
// You need to return SOMETHING here to remove the warning
return 0;
}
如果emptyHeapArray(h)
返回true,則不返回任何內容。 然后控件到達非無效函數firstHeapArray
。
編譯器推斷, if
測試失敗,則沒有return語句if可以執行。
事實上firstHeapArray
不返回如果emptyHeapArray(h) == true
。
這是未定義的行為,這意味着可能發生任何事情,很可能在堆為空時使用此函數的任何人都可能會收到隨機值。
您可以處理這種情況,返回成功標志:
bool firstHeapArray (IntHeapArray h, int * out_value) {
if(!emptyHeapArray(h))
{
*value = h.array[0];
return true; //success
}
return false;
}
無論哪種情況,此函數都必須返回值:
int firstHeapArray (IntHeapArray h) {
if(!emptyHeapArray(h))
return h.array[0];
return 0;
}
在您的示例中,僅當滿足某些條件時,它才返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.