I want to shorten the amount of if statements in my code. I am currently writing a text based adventure game in C, I am loosely basing this on my knowledge of the original D&D games by TSR. So I have the standard stats and their bonuses. What I want to do is if it is possible to remove the many lines of 'if' statements that I have.
As you can see I have many of them. I have thought of using some type of for loop that can check the score and give the bonuses accordingly without needing 5-6 if statements for each score. Any thoughts will help.
Are you sure with numbers? I do not remember any edition which have such bonuses. Your bonus distribution cannot be expressed in short mathematic formula. So chain of if/elseif is yout best bet.
When you do if statements testing the same variable, you should probably use elseif i.e
1 2 3 4 5 6 7 8 9 10 11 12 13
int bla = 1;
if(bla == 1){
// do stuff
}
elseif (bla == 2){
// do other stuff
}
elseif (bla == 3){
// do other stuff
}
else{
// any other case do this stuff
}
In this case however I don't know if a switch statement is good either. Perhaps you should just try making an algorithm to determine these bonus effects.
Actually, your if statements might be just fine. You basically have several arbitrary piecewise functions -- that pretty much warrants a bunch of if statements.
The ternary operator might help you out: result = (condition) ? (true_outcome) : (false_outcome)
You might identify some patterns that would enable you to generalize, like (random example) "the hit bonus starts at zero and increases by 1 with every 3rd point of strength after 6," so: hitbonus = str > 6 ? (str - 6) / 3 : 0 ;
You could also populate a look-up table.
But whilst that could be shorter, it isn't necessarily any clearer or easier. I'd just suggest keeping the calculations in a tidy place. Perhaps create an object CharacterSheet to manage this scorekeeping. Just make sure the calculations are the job of one specific part of your code, and don't duplicate the implementation of that functionality.