<分区>
当我意识到我忘记了函数中的 return 语句时,我注意到了这一点,但我仍然得到了预期的值。因此,我尝试在一个简单的程序中重现这种情况,它做了同样的事情——返回了预期的值,但没有明确的 return 语句。
我注意到,如果我将 printf 格式说明符类型从 f
更改为 d
,它就不起作用了。或者,如果我创建一个名为 double tau = 6.2830
的变量,但具有多个返回类型的变量会导致返回最后定义的变量。
所以我的结论是,这是编译器纠正我的错误的工作,但这似乎没有多大帮助,我希望这是一个错误,而不是使用 -Wall 时隐藏的警告
或其他一些相关标志。
我的结论是否正确?这个设计决定背后的原因是什么?
#include <stdio.h>
float pi() {
float pi = 3.1415;
// float tau = 6.2830; // this will now return instead
// double cthulhu = -000000.000000011101; // this will not allow it to work
}
int main() {
float num;
num = pi();
printf("Some number is %f", num); // changing %f to %d will also not allow it to work
return 0;
}
编译为
g++ test.cpp -o test
输出
$ ./test
Some number is 3.141500
带有 -Wall 标志的编译器输出
a.cpp: In function ‘float pi()’:
a.cpp:4:11: warning: unused variable ‘pi’ [-Wunused-variable]
float pi = 3.1415;
^~
a.cpp:5:1: warning: no return statement in function returning non-void [-Wreturn-type]
}