If you want to talk about security, then
neither program is secure: Your program can invoke undefined behavior if your user input fails, or if the user enters the value 0 for b. This is because you have uninitialized values, and you divide by b without checking to see if b != 0, respectively.
Also, for security: If your user enters two values that will cause overflow when added or multiplied together, you will also have undefined behavior. So if you want to have perfect security, you need better
input sanitization.
• Using an uninitialized variable in an operation is undefined behavior.
• Integer division by 0 is undefined behavior.
• Integer overflow is undefined behavior.
Undefined behavior is a security hole, because it causes your program to be able to do
anything. In most cases, your program will just spit out junk or crash, but for a complicated program, undefined behavior could have devastating consequences downstream.
As for efficiency, in this excerpt, you will not notice any trace of a difference:
Pre-optimization is the root of all evil -Don Knuth
Technically, on a compiler that optimized literally nothing, your second program will use sizeof(int)*2 more memory, but this is so immaterial that it does not matter.
Readability and maintainablity is much more important than wringing out efficiency, in most practical cases.
So that then raises the question of which program is more readable and/or maintainable? For such a simple program, they are both about the same. But if you wanted to expand your program to do other operations beyond what you just did, your second program is more maintainable because you saved your previous operations instead of overwriting them.
In C++ (or modern C), you don't have to declare all your variables at the beginning of a function. You can declare them right when you need them, like this.
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
|
#include <iostream>
int main()
{
using std::cout;
using std::endl;
int a = 0; // default value in case cin fails
int b = 1; // default value in case cin fails
cout << "Insert a number." << endl;
std::cin >> a;
cout << "Insert another number." << endl;
std::cin >> b;
int sum = a + b;
cout << "Sum: " << sum << endl;
int mult = a * b;
cout << "Multiplied: " << mult << endl;
if (b == 0)
{
cout << "Divided: error div by 0!" << endl;
}
else
{
int div = a / b;
cout << "Divided: " << div << endl;
}
return 0;
}
|
Again though, this is such a small program that I'd say that doesn't really improve or decrease readability or maintainability.
Also, your operator on your second program's line 9 is wrong.