Consider a function foo()
that might never exit:
int foo(int n) {
if(n != 0) return n;
else for(;;); /* intentional infinite loop */
return 0; /* (*) */
}
Is it valid C to omit the final return-statement? Will it evoke undefined behavior if I leave out that final statement?
You can omit the last return
statment which is after an indefinite loop. But you may be getting compilation warning like not all path are returning. Its not good to have an indefinite loop in a function. Keep one condition to break the loop.
If that indefinite loop is really required in that case anyway the return
statement after that is a dead code. Removing that will not be undefinite behaviour.
即使它没有返回语句也返回,除非你使用返回值,否则没有UB。
For a non- void
function, it is valid to have no return
statements at all or that not all the paths have a return
statement.
For example:
// This is a valid function definition.
int foo(void)
{
}
or
// This is a valid function definition.
int bar(void)
{
if (printf(""))
{
exit(1);
}
return 0;
}
but reading the return value of foo
is undefined behavior.
foo(); // OK
int a = foo(); // Undefined behavior
int b = bar(); // OK
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.