Programming tips 1
The not-good solution
In this solution, we use an expression to multiply num by 2, and then assign that value back to num. From that point forward, num will contain our doubled number.
Why this is a bad solution:
- Before the assignment statement, num contains the user’s input. After the assignment, it contains a different value. That’s confusing.
- We overwrote the user’s input by assigning a new value to the input variable, so if we wanted to extend our program to do something else with that input value later (e.g. triple the user’s input), it’s already been lost.
This solution is pretty straightforward to read and understand, and resolves both of the problems encountered in the worst solution.
The primary downside here is that we’re defining a new variable (which adds complexity) to store a value we only use once. We can do better.
This is the preferred solution of the bunch. When std::cout executes, the expression num * 2 will get evaluated, and the result will be double num‘s value. That value will get printed. The value in num itself will not be altered, so we can use it again later if we wish.
This version is our reference solution.
Comments
Post a Comment