Re variables, you have the old way of declaring variables at the top of a function. Old C compilers needed that and it stuck, with humans making excuses for why they still did it afterwards (I think).
Best practice these days is declaring them as close to where they are used as is sensible. In your code, for example, all of the current_XXX
variables can be declared inside the while loop. Same with valid_units
, but there’s a reason for keeping that at the top of main or somewhere more visible since it’s important data that maybe should be visible in case you want to extend the list.
Declaring variables over and over in a loop also might seem wasteful, but optimizing compilers do a good job of identifying all sorts of things that can be… well… optimized so trusting the compiler is a good thing. Up to a point, as with everything.
Also you can if (invalid_unit)
instead of adding == true
, something which is true for any variable that can resolve to a boolean in some way, like a number where non-zero is true. In C++ you can also use not
and and
keywords in place of !
and &&
hieroglyphics. MSVC needs a compiler flag to enable standard C++ and to use them.
Also setting variables to the same value:
// First run, smallest_length and largest_length are the same
if (not has_ran_once) {
smallest_length = largest_length = previous_length = current_length;
smallest_unit = largest_unit = previous_unit = current_unit;
smallest_meters = largest_meters = previous_meters = current_meters;
has_ran_once = true;
}
Watch out for the comments too:
// Check equal
if(current_meters == previous_meters)
This one is completely unnecessary because everybody knows what the very next line does and often naming variables and functions well means we don’t have to add comments at all.
Kind of the same with:
// After first run
else if(has_ran_once == true){
… although there and in the first else if
you would be better off with just an else
since there is no else
or else if
s after the else if
and it’s operating on a two state boolean anyhoo. In the case of using just an else
that comment would be okay since there’s no expression describing what’s happening.
Of course none of that matters at the moment apart from having them in the back of your mind.