编辑
部分 6.9.1 函数定义段落 12 表示:
clang 默认会发出警告, gcc 会警告 -Wall ,一般来说你应该启用警告。
I bumped into this problem when I forgot to write the return clause of a function, but there was no warning or error in gcc. I fixed it but started wondering why the function would return something meaningless without a return. Here are some examples I tried:
#include "stdio.h" #include "stdlib.h" int func1 () { int i; i = 2; } int func2 (int a) { int i = a+3; } int func3 () { int i; for (i = 0; i <= 1; i++); } int main(void) { int a = 0; int b = 0; int c = 0; a = func1(); printf("a = %d \n", a); b = func2(a); printf("b = %d \n", b); c = func3(); printf("c = %d \n", c); }
And the results are:
a = 1 b = 4 c = 7
My questions:
1) why these results? Is there any general rule for this?
2) why keep this thing rather than report an error? Can it be somehow 'useful' somewhere?
This is undefined behavior and will depend on the calling convention being used. If the caller is expecting the result in a register then whatever value was last in the register will be used.
Edit
The draft C99 standard in section 6.9.1 Function definitions paragraph 12 says:
clang will warn by default and gcc will warn with -Wall, in general you should enable warnings.
这篇关于如果没有明确的“回报”,函数将返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!