View more

View more

View more

Image of the Day Submit

IOTD | Top Screenshots

The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

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

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

17 replies to this topic

#1warnexus  Prime Members

Posted 17 April 2014 - 02:53 PM

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, 17 April 2014 - 06:34 PM.

#2ikarth  Members

Posted 17 April 2014 - 03:41 PM

POPULAR

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?

#3JohnnyCode  Members

Posted 17 April 2014 - 04:01 PM

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.

#4ferrous  Members

Posted 17 April 2014 - 04:31 PM

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, 17 April 2014 - 04:31 PM.

#5Juliean  Members

Posted 17 April 2014 - 04:46 PM

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)
{
return;
}

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

void doSomething(void)
{
if(true)
{
return;
}
}


Edited by Juliean, 17 April 2014 - 04:46 PM.

#6warnexus  Prime Members

Posted 17 April 2014 - 06:25 PM

I added a more specific code to my situation above.

#7SeanMiddleditch  Members

Posted 17 April 2014 - 06:34 PM

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.

Game Developer, C++ Geek, Dragon Slayer - http://seanmiddleditch.com

C++ SG14 "Games & Low Latency" - Co-chair - public forums

Wargaming Seattle - Lead Server Engineer - We're hiring!

#8Álvaro  Members

Posted 17 April 2014 - 08:02 PM

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)

#9Vortez  Members

Posted 17 April 2014 - 09:45 PM

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, 17 April 2014 - 09:47 PM.

#10warnexus  Prime Members

Posted 17 April 2014 - 10:58 PM

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.

#11Satharis  Members

Posted 18 April 2014 - 06:50 PM

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.

#12ikarth  Members

Posted 18 April 2014 - 07:48 PM

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.

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


Edited by ikarth, 18 April 2014 - 07:56 PM.

#13Buster2000  Members

Posted 19 April 2014 - 01:31 AM

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.

#14warnexus  Prime Members

Posted 19 April 2014 - 07:40 AM

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.


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;

}

}



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.

#15Álvaro  Members

Posted 19 April 2014 - 08:31 AM

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.

#16ikarth  Members

Posted 19 April 2014 - 02:57 PM

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.

#17warnexus  Prime Members

Posted 19 April 2014 - 04:02 PM

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.

#18Satharis  Members

Posted 19 April 2014 - 11:44 PM

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, 19 April 2014 - 11:45 PM.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.