Followers 0

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

## 17 posts in this topic

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;
}

}

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
0

##### Share on other sites

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.

0

##### 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
0

##### Share on other sites

I added a more specific code to my situation above.

0

##### 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.
0

##### 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)
0

##### 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
2

##### 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.

1

##### 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.
0

##### 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();
}

// check for leveling
int xp_per_level = 15; // defining this so it's not a magic number

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
0

##### 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.
1

##### 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();
}

// check for leveling
int xp_per_level = 15; // defining this so it's not a magic number

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.
0

##### 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.
0

##### 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.

0

##### 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.

0

##### 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
0

## Create an account

Register a new account