bool SomeFunction()
{
}
我无法在我的机器上运行Borland C ++,但我需要从C ++转换为VB,因此需要有关此功能的帮助。
答案 0 :(得分:10)
该函数声称它返回bool
但它什么都不返回。这应该导致编译器警告。如果使用它来分配某些东西调用该函数,结果将是未定义的行为:
bool b = SomeFunction(); // UB, SomeFunction is failing to return.
SomeFunction(); // still undefined behaviour
只允许main()
不显式返回,在这种情况下,它会隐式返回0
。
见这里:
§6.6.3/ 2:
离开函数末尾相当于没有值的返回;这会导致值返回函数中的未定义行为。
答案 1 :(得分:1)
我在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
将为true。在我的系统上,这总是正确的,但这取决于上下文。此外,您可能会得到不同的调试和发布结果。
结论当然是x未定义。给定的代码有点像写
bool x;
if (x)
{
// ...
}
我倾向于认为SomeFunction()
的定义不仅应该触发编译器警告,还应该触发错误。 Visual C ++这样做,我不知道其他编译器。
答案 2 :(得分:-1)
应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;
}