exit() to end a function
Jonathan M Davis
jmdavisProg at gmx.com
Sat Feb 12 14:48:56 PST 2011
On Saturday 12 February 2011 14:03:09 bearophile wrote:
> A small D2 function:
>
> import std.c.stdlib: exit;
> int foo(int x) {
> if (x > 0)
> return x;
> exit(0);
> //assert(0);
> }
> void main() {}
>
>
> DMD 2.051 gives this compile-time error:
> test.d(2): Error: function test4.foo no return exp; or assert(0); at end of
> function
>
> If I comment out the the final exit(0) and uncomment the assert(0), the
> code compiles correctly. Is it meaningful and good to give
> std.c.stdlib.exit the same function-end semantics of assert(0)?
>
> GCC has a "noreturn" function attribute that allows to tell the compiler
> what functions (beside few default ones like exit) don't return:
> http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#index-g_t_0040c
> ode_007bnoreturn_007d-function-attribute-2464
The problem is that we have no way to indicate that a function will never
return. So, even if it's a function like exit which kills the program or a
function which always throws, the compiler doesn't know that the next statement
will never be executed. As such, it requires the assert(0).
Considering that exit really isn't something that you should be calling
normally, I don't think that there's much value in complicating dmd just for it.
There would be some value to having an attribute which indicated that a function
never returns under any circumstances (likely since it always throws), but that
wouldn't help exit any, since it's a C function and wouldn't have the attribute.
Regardless, I see little value in complicating dmd even a little bit more just
so that you don't have to insert an extra assert(0) after exit - particularly
when very few programs call exit, and very few should. Generally, something is
horrendously wrong if exit is being called, and there's probably a better way to
handle it.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list