16) IF Statements and FLAGS¶
This is honestly my favourite thing to use with IF statements, it just makes things SO much easier.
Here’s some code for checking a leap year.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
If you’ve never done the code for a Leap year before, now you know it’s that.
If you think there’s too many lines and you could just write one
cout statement to say cout << "Leap year" << endl; or cout << "Not a Leap Year" << endl then yes, you can in fact do that. But I did this on purpose.The code works fine, but the problem is that it repeats itself.
It’s either a Leap Year or it’s not a Leap Year, and we have multiple conditions to check, but the thing is, if mutliple of those end up doing the same thing, then there’s a lot of repetition involved. So, we use Flags to reduce that repitition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
The {} aren’t necesary when only line line is written after the IF or ELSE body, but I kept them because it’s easier to see which
else statement belongs to which if statement.Anyways. You might be looking at that and thinking that this only increased the number of lines being used.
Well you’d be right, but not for long. If the part being repeated was longer, or if there were more repititions, then the code would very easily become shorter with flags. The point is to reduce repetitions so the number of lines is less, and in some cases it can also be used to make sure there’s only one output. I can’t show the code since it was around 200 lines but Flags were the key in making sure that Output statements also didn’t end up repeating themselves. Before flags, the line count was above 800.