Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have successfully compiled and executed the following code in gcc:

#include <stdio.h>

int foo()
{

}

int main()
{
    int i = 12345;
    i = foo();
    printf("i is: %d", i);
}

The output is:

i is: 0

So gcc allowed me not to return from the function foo() and made foo() return 0.

Does this behavior only applies to gcc or do other C standards also have it (based on my understanding, gcc does not conform to any C standard)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
378 views
Welcome To Ask or Share your Answers For Others

1 Answer

None of the C standards require the compiler to produce an error or warning if a function is missing a return statement1.

In all of the C standards the behaviour is undefined if control flow reaches the end of non-void function without a return and the return value of the function is then used (as in your code).

So if by "allow" you mean "specify it as legal, well-defined behaviour", none of the C standards allow your code. If you just mean "don't require an implementation to produce an error", all of them do.

Do note that the value of i in your example program can easily change if you change the definition of foo (without adding a return). You can not rely on it being 0. There is no rule that says "if there's no return, return 0" - neither in the standard nor in GCC's implementation. According to the standard it's undefined and in GCC it will just be whatever happens to be in the return register at that time.


1 In the general case this would be undecidable. One could do what e.g. Java does and define the rules so that some otherwise valid function definitions are rejected, but none of the C standards do this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...