Code Optimization

In what ways could the following code be optimized? It's a basic program state function to all function loops based on its state.

main.ccp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include "numberfunction.h"
using namespace std;
int number{0};

int main() {
while (number==0)
{
cout << "Please input 1";
int inputnumber;
cin >> inputnumber;
number = returnnumber(inputnumber);
}
while (number == 1)
{
cout << "number is now 1";
}
return 0;
}


numberfuncion.h
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

returnnumber(int x)
{
if (x == 1) { return 1; }
	else { return 0; }
};
Last edited on
"The greatest optimization is when the code goes from not working to working." - Ron Hiller ( a former co-worker).

This program will never terminate because the loop at lines 14-17 will run forever.

To optimize it, get rid of returnnumber and inputnumber and do the comparison in the loop.

Some other comments:

main.cpp:
Indent the code to match the block structure.
Line 3: Get out of the habit of using namespace std;. Instead, use just the symbols that you need.
Line 7: If a loop will always execute once then code it as a do-while loop.
Line 9: Put a space at the end of the string
Line 14: get rid of the while loop.
Line 16: add a newline (\n) to the end of the string.

numberfunction.h:

It's good to declare functions in a header file, but don't put the code there. If your program grows to multiple source files and they each include this header, you'll get "multiply defined symbol" errors.

Line 2: Don't put using namespace std; in a header file because that will continue to apply to all other header files that you might include later in your program. This can lead to unexpected errors.

Line 4: Functions must have a return type.

Lines 6-7: You could replace this with return (x == 1);, but chances are excellent that the compiler will optimize either one to the same machine code. But like I said above, there's really no need for the function at all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using std::cin;
using std::cout;

int number{0};

int
main()
{
    do {
	cout << "Please input 1: ";
	cin >> number;
    } while (number != 1);
    
    cout << "number is now 1\n";
    return 0;
}

even with such a small program I would not use the global.

optimization of code with prints and reads ... this program is going to spend like 90% of its time waiting on the user to type stuff, 5% of its time writing the same line of text over and over, and 5% or less of its time executing code.

if you want it to run fast, put the inputs in a file, remove the useless output, and print once when it gets out of the loop that number has changed.
Last edited on
Topic archived. No new replies allowed.