Is there a way to break out of an if statement without "hacking the code"?

Started by
16 comments, last by Satharis 9 years, 12 months ago

I noticed I cannot use a break statement inside of an if statement. I'm using Java.

Compiler will complain to the following:

if(true)

{

break; // invalid code

}

This lead me to have habits of hacking the code everything I cannot break out of the if statement.

I would usually set the boolean flag to false right after execution has been done once because I just want the code to execute once.

EDIT:

Example of hacky approach: The code written below is used for when a character has leveled up in-game. The current level gets incremented, the current and max hp gets updated. The current hp gets updated to the updated max level. Upon level up, the level up logo renders upward above the character and disappears once it has reached a certain final point(this will be dictated by some fixed height in the game code).

All the code will appear in the main character update method.

NOTE: levelUp = true triggers everything(all the hp data to be updated and level up Logo effect to happen.)


public void update()
{
        if(exp >= 15 && (level < maxLevel))
       {
              levelUp = true;
              exp = 0;
       }
 
       if(updateLevel && (level < maxLevel) )
       {
              level++;
              updateLevel = false;
       }
 
       // update current hp
       if(updateCurrenHpAfterLevelUp)
       {
               if(life < maxLife)
               {
 
                     life++;
 
               }
 
               if(life == maxLife)
               {
                     updateCurrenHpAfterLevelUp = false;
               }
 
       }
 
 
        // updates maxHp
        if(updateMaxHpAfterLevelUp)
        {
                  if(maxHpCounter < maxHpIncrease)
                  {
                          maxLife++;
                          maxHpCounter++;
 
                  }
 
 
 
                   if(maxHpCounter == maxHpIncrease)
                   {
                          maxHpCounter = 0;
                          updateCurrenHpAfterLevelUp = true;
 
                          updateMaxHpAfterLevelUp = false;
 
                   }
         }
 
                   if(levelUp)
                   {
 
 
                         levelUpLogo.update();
 
 
                         if(levelUpLogo.getHeightIncrease() == levelUpLogo.getMaxHeight())
                         {
                                   levelUp = false;
                                   updateMaxHpAfterLevelUp = true;
                                   updateLevel = true;
 
                                   levelUpLogo.setHeightIncrease(0);
                         }
                   }
 
 
}
Advertisement

What you are asking for is essentially a goto. Usually this is a sign you should rethink your control flow. There may be a way to get the behavior you want more easily, without needing to have as many if statements.

You could look at loop flow control, break and continue, or a switch statement, depending on what behavior you are looking for.

It's a bit hard to advise you on what the exact thing you need is without a more specific example. Can you post an example from your current code where you are running into this issue?

I would usually set the boolean flag to false right after execution has been done once because I just want the code to execute once.

I do not see though why would execution return before the if again, is it in a cycle?

In case you do not wish the code to continue inside the if upon some condidtion, nested if is what I would do.

In case the if is in a cycle and you wish it to run only once- you should move it out of cycle primarily if you can.

In case the execution once wish to run it , once not, keep condition altering as you do.

Anyway, it is always a very particular problem, and one has always many ways to rethink what he is performing and how.

Without criticizing the very concrete code of yours, we cannot give you a definite advice on this.

Honestly kind of hard to tell what it is you need though, you may have to expand on what you are trying to solve, but that said...

Some things to think about, if you are in a loop, you can use the continue keyword, though I know some people won't approve, as they prefer to have as simple of a control flow as possible (which you could get by rearranging your code) As debugging anything that jumps around all over the place is a pain.

Or you might need to rejigger it to be a function that returns a boolean, then you can just return as soon as you've gotten far enough.

Kind of like ferrous said, but your best bet probably is to pack that whole thing in a seperate function, and just return where you would break otherwise:


// so thats what you want:

if(true)
{
    break;
}

// pack the whole if-body in a external function:

if(true)
{
     doSomething();
}

void doSomething(void)
{
    // instead of break, return
    return;
}

// or, put the whole condition in here if it fits better:

void doSomething(void)
{
      if(true)
      {
             // instead of break, return
             return;
      }
}

I added a more specific code to my situation above.

This is also quite hacky, but if you're interested in Dumb Programmer Tricks, here's one for you:

for (bool once = true; once; once = false) {
  // stuff that happens at most once

  if (early_exit)
    break; // 'continue' would also work

  // other stuff that happens at most once
}
I have blissfully never seen this kind of code in the wild, aside from some gnarly pre-C++11 macros for emulating range-based-for.

Decomposing your logic into separate functions is a _significantly_ better idea, of course.

Sean Middleditch – Game Systems Engineer – Join my team!

In the same line as SeanMiddleditch's hack:
#define breakable_if(X) for (bool breakable_if_var = X; breakable_if_var; breakable_if_var = false)

Your approach seem a bit hackish if you want my opinion. Perhaps you should refactor and encapsulate more code into classes that would take care of the leveling up process and manage the player health ect? Your code is very hard to read/understand atm to be honest. You might consider splitting those things up into functions.


Your approach seem a bit hackish if you want my opinion. Perhaps you should refactor and encapsulate more code into classes that would take care of the leveling up process and manage the player health ect? Your code is very hard to read/understand atm to be honest. You might consider splitting those things up into functions.

Fair enough. Thanks for the feedback.

This topic is closed to new replies.

Advertisement