簡體   English   中英

Borland C ++這個bool函數會返回什么?

[英]Borland C++ What wil this bool function return?

bool SomeFunction()
{

}

我無法在我的機器上運行Borland C ++,但我需要從C ++轉換為VB,因此需要有關此功能的幫助。

該函數聲稱它返回一個bool但它什么也沒有返回。 這應該導致編譯器警告。 如果你 使用它來分配 調用函數的 東西 ,結果將是未定義的行為:

bool b = SomeFunction(); // UB, SomeFunction is failing to return.
SomeFunction(); // still undefined behaviour

只允許main()不顯式返回,在這種情況下它隱式返回0

看這里:

§6.6.3/ 2:

流出函數末尾相當於沒有值的返回; 這會導致值返回函數中的未定義行為。

我在Borland XE2上編譯了以下代碼:

bool SomeFunction()
{
}

int main()
{
    bool x = SomeFunction();
    // ...
}

SomeFunction()轉換為以下x86匯編程序代碼:

push ebp
mov ebp,esp
pop ebp
ret

main()的賦值轉換為:

call SomeFunction()
mov [ebp-$31],al

其中[ebp-$31]x的位置。 這意味着,寄存器al的內容將以bool x結尾。 如果al為0,則x為false,否則x為真。 在我的系統上,這總是正確的,但這取決於上下文。 您也可能會獲得不同的調試和發布結果。

當然,結論是x未定義。 給定的代碼有點像寫作

bool x;
if (x)
{
    // ...
}

我傾向於認為SomeFunction()的定義不僅應該觸發編譯器警告,還應該觸發錯誤。 Visual C ++這樣做,我不知道其他編譯器。

它應該return true; 或者return false;

bool SomeFunction()
{

    return true;

    // or

    return false;

}

如果您的編譯器沒有內置bool,那么您可以這樣做:

typedef int bool;
#define true 1
#define false 0

int main(void)
{

    bool answer;
    answer = true;

    while(true)
    {

    }

   return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM