• Advertisement
Sign in to follow this  

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

This topic is 1370 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);
                         }
                   }
 
 
}
Edited by warnexus

Share this post


Link to post
Share on other sites
Advertisement

 

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.

Share this post


Link to post
Share on other sites

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.

Edited by ferrous

Share this post


Link to post
Share on other sites

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;
      }
}
Edited by Juliean

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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)

Share this post


Link to post
Share on other sites

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.

Edited by Vortez

Share this post


Link to post
Share on other sites


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.

Share this post


Link to post
Share on other sites
Even taking a quick peek at the code I'd say you can probably significantly streamline the branching just by following the advice about breaking some of the code into more functions. Leveling up for example could quite easily be a function in itself.

Share this post


Link to post
Share on other sites
Have to agree; what you really want here is a state machine, or at least several functions.
 
Part of your problem is that you're trying to handle event-based stuff in a polling update loop. You can do it that way, but it will make your life much easier if you break things like incrementing XP into their own function. That way, instead of checking every time it goes through the input loop, it'll only get called when the character actually needs to check for leveling up.
 
[source lang="java"]
public void levelUp() {
   if(level >= maxLevel) {
      return;
   }
   int hp_per_level; // defining this so it's not a magic number
   maxHp = min(maxHp + hp_per_level, maxHpIncrease);
   life = min(life + hp_per_level, maxHp);
   levelUpLogo.play();
}
 
// Call this whenever your character adds XP
public void addXP(int exp_to_add) {
   // check for leveling
   int xp_per_level = 15; // defining this so it's not a magic number
   exp += exp_to_add;
 
   if (exp > xp_per_level) {
      levelUp(); // level up
      exp = 0; // this resets exp to 0 after every level, you may want to have it instead be: exp -= xp_per_level;
   }
}
[/source]
Edited by ikarth

Share this post


Link to post
Share on other sites
Obviously the correct way to fix this is to refactor your code. You shouldn't need to exit an if without it completing but if you really wanted to do it the hacky way in Java you can use a labeled break which is effectively a goto.

The only place I've seen labeled breaks actually used in production code was when doing J2ME ports of megadrive games where we had the original ASM code in comments and then the Java was a line by line reimplementation including jumps and inclined data.

Share this post


Link to post
Share on other sites

Have to agree; what you really want here is a state machine, or at least several functions.
 
Part of your problem is that you're trying to handle event-based stuff in a polling update loop. You can do it that way, but it will make your life much easier if you break things like incrementing XP into their own function. That way, instead of checking every time it goes through the input loop, it'll only get called when the character actually needs to check for leveling up.
 
[source lang="java"]
public void levelUp() {
   if(level >= maxLevel) {
      return;
   }
   int hp_per_level; // defining this so it's not a magic number
   maxHp = min(maxHp + hp_per_level, maxHpIncrease);
   life = min(life + hp_per_level, maxHp);
   levelUpLogo.play();
}
 
// Call this whenever your character adds XP
public void addXP(int exp_to_add) {
   // check for leveling
   int xp_per_level = 15; // defining this so it's not a magic number
   exp += exp_to_add;
 
   if (exp > xp_per_level) {
      levelUp(); // level up
      exp = 0; // this resets exp to 0 after every level, you may want to have it instead be: exp -= xp_per_level;
   }
}
[/source]


Interesting, I notice a return statement that returns no value in the if statement. What or where will the code be when the code reaches return.

Share this post


Link to post
Share on other sites

Interesting, I notice a return statement that returns no value in the if statement. What or where will the code be when the code reaches return.


That's a very confused question. `return' quits the function, whether it returns with a value or without it. The execution will continue wherever the function was called.

Share this post


Link to post
Share on other sites

 

Interesting, I notice a return statement that returns no value in the if statement. What or where will the code be when the code reaches return.


That's a very confused question. `return' quits the function, whether it returns with a value or without it. The execution will continue wherever the function was called.

 

Specifically, addXP will be called [em]first[/em]. If exp is greater than 15, it will call levelUp(). The levelUp() function will check to see if maxLevel has been reached. If it has, it will return from there with no return value because these are void functions. The return takes it back to the addXp() function at the point it was called, and the next line is executed, in this case setting exp to 0.

 

Step through your running code in a debugger, it will give you a much better idea of what is going on under the hood.

Share this post


Link to post
Share on other sites

 

Interesting, I notice a return statement that returns no value in the if statement. What or where will the code be when the code reaches return.


That's a very confused question. `return' quits the function, whether it returns with a value or without it. The execution will continue wherever the function was called.

 

Oh Okay. That was the answer I was looking for. Apologies for rewording the question incorrectly.

Share this post


Link to post
Share on other sites

Oh Okay. That was the answer I was looking for. Apologies for rewording the question incorrectly.


Just think of it like returning a value, at any point in your code a function might return a bool or something, you've probably seen or used code like this before.
 
if (somecondition)
{
    dosomestuff;
}
else
{
    otherstuff;
    if (someothercondition)
    {
        return true;
    }
}

return false;
In a void function you can just return without a value, so for all intents and purposes it basically works like a break statement out of the function. Edited by Satharis

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement