Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should the function attribute noreturn be used in C? [closed]

Tags:

c

function

void

I've recently found out about this attribute(I'm referring to c, not c++, as I'm working on a c project which has a library where an equivalent is defined and it's destined only for c usage). When is it considered good practice to use it? In all void function declarations? Are there any exceptions?

like image 233
octavian Avatar asked Feb 08 '14 13:02

octavian


1 Answers

Don't do that for your void functions, this would have undefined behavior.

The new C11 construct _Noreturn should only be used when you know that your function will never return to the caller. This can e.g be the case when it unconditionally makes a call to abort, exit or alike, or when you enter an infinite loop.

The purpose of that is that the compiler can optimize the call on the calling side, in particular by cutting off the whole branch of execution that comes after the call.

Generally void functions are not of that kind, they return to the caller, just that on that return they don't provide a value that will be used. For most such functions declaring them is fundamentally wrong.

The C11 syntax is _Noreturn or with a macro noreturn. Not all compilers do yet implement that feature, but most have extensions to C99 (or C89) that provides the same feature. On that platforms you can usually define a macro noreturn that would be an upward compatible replacement.

like image 200
Jens Gustedt Avatar answered Nov 03 '22 06:11

Jens Gustedt