Michael Nguyen
Michael Nguyen

Reputation: 123

c++ if statement with a return outside of the block

Sorry if this is a duplicate post as I don't even know the right words to use to search for it.

I can across some c++ code that looks like this:

void start()
{
  if (call(initialize())) return;
  {
    // the rest of the code runs here
  }
  terminate();
}

Am I missing something or is this just code obfuscation by somebody who hates everyone else who have to read this code?

Upvotes: 2

Views: 72

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Am I missing something

Not really, no.

is this just code obfuscation by somebody who hates everyone else who have to read this code?

That, or it's a mistake (e.g. missing else, or the return; shouldn't be there).

If the code in the block really needs to be in a block (which is certainly not impossible — this is a common way to control scope), then it should at least be preceded by a blank link to make clear that it has nothing to do with the if statement.

The code might be better written like this:

void start()
{
   if (call(initialize()))
      return;

   {
      // stuff in a block
   }

   terminate();
}

Even here I would almost certainly include a proper comment inside the block scope, both to explain why it was necessary (if not self-evident) and to in turn implicitly re-assure that it's not some accidental misformatting of an if/else chain.

Upvotes: 3

Related Questions