user3310334
user3310334

Reputation:

Do i need a return statement after an infinite loop?

Is this good code (is it readable, will the compiler compile it):

int is_thing_five() {
  while (1) {
    if (thing_is_ready) {
      return thing == 5;
    }

    update_thing();
  }
}

or does it have to have a return statement after the infinite loop

int is_thing_five() {
  while (1) {
    if (thing_is_ready) {
      return thing == 5;
    }

    update_thing();
  }
  return 0;
}

Upvotes: 1

Views: 352

Answers (2)

Bathsheba
Bathsheba

Reputation: 234785

In C, the behaviour of using a return value from a non-void function that does not have an explicit return value is undefined.

So, no you don't need the return statement, and you wouldn't need it even if the end of the function was reachable, so long as a caller of the function doesn't use the return value.

int main is an exception to this rule: you are allowed to call main from itself (indirectly or otherwise), and you are allowed to assume an implicit return 0; on any branch that doesn't have an explicit return value.


Interesting, before C11 the behaviour of a function with an infinite loop that "did nothing" was undefined. But C11 defines the behaviour by way of a footnote in the standard:

C11, 6.8.5 ad 6:

An iteration statement whose controlling expression is not a constant expression,156) that performs no input/output operations, does not access volatile objects, and performs no synchronization or atomic operations in its body, controlling expression, or (in the case of a for statement) its expression-3, may be assumed by the implementation to terminate.157)


157)This is intended to allow compiler transformations such as removal of empty loops even when termination cannot be proven.

Upvotes: 3

Tom Tanner
Tom Tanner

Reputation: 9354

Well, you don't needed it. Some compilers however will give you a warning which you would suppress with a pragma, or suppress by having an extra return. And then that might also get you a warning on a different compiler, because the statement is unreachable.

For that piece of code, I'd try to move the if test into the while, so you have

int is_thing_five() 
{
    while (not thing_is_ready)
    {
         update_thing();
    }
    return thing == 5;
}

which is somewhat clearer as it doesn't have an infinite loop with a test to break out of it in the middle.

Upvotes: 0

Related Questions