Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

c - What is the result of calling return in a non-void function after calling a function returning int?

UPDATE 2018: This was an old question I wrote with reduced understanding of C. Please refrain from downvoting.


When I use the following code:

int mytest(void);
int main(void)
{
   mytest();
   return;
}
int mytest(void)
{
   return 3;
}

What is the return value of main? I understand this is

  • undefined behavior
  • might produce an error

Edit: large comment: I know this is undefined behavior. Logically, what return value will be produced?

Edit 2: Sample: http://ideone.com/fAxnNn

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is not a desired behaviour, though not explicitly mentioned as undefined behaviour. This is a "Constraints violation".

Quoting C11, chapter 6.8.6.4

[...] A return statement without an expression shall only appear in a function whose return type is void.

and, from chapter §5.1.1.3, Diagnostics,

A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint, even if the behavior is also explicitly specified as undefined or implementation-defined. [....]

In this case, compiler proceeds to generate the executable code, so, yes, executing this binary invokes undefined behavior.

Bottom line, for main() which is expected to return an int should not have a return statement without an expression. Refrain from writing code like that.


[Note: As per this discussion, there's a strong notion that this is undefined behaviour, but still, there's no explicit mention in the standard.]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...