Reputation: 23
I'm new to programming and I have been messing around with a bit of C++. I have a simple program that works, but I have a lot of similar functions that I want to get rid of. I figured I would just use a function for it and add parameters that I can change, but in an if-statement I have the function call itself back so it could run the same function again.
So my question trying to find a work around so I can simplify the similar functions. In the code I have provided there are only a few differences between function 1 and 2. In my actual program I have about 8 of these similar functions.
int a;
// function 1
int ba = 0;
int bb = 0;
int bc;
// function 2
int ca = 0;
int cb = 0;
int cc;
void function2() {
cin >> a;
if(a == 1) {
ca = ca + 10000;
cb = cb + 100;
function2();
}
if(a == 0) {
cb = cb + 100;
function2();
} else {
cc = ca / cb;
}
}
void function1() {
cin >> a;
if(a == 1) {
ba = ba + 10000;
bb = bb + 100;
function1();
}
if(a == 0) {
bb = bb + 100;
function1();
} else {
bc = ba / bb;
}
}
int main() {
function1();
function2();
}
Upvotes: 1
Views: 120
Reputation: 2361
The example you've posted doesn't require any function parameter...
First, you'd better use a loop instead of a tail recursion. It would better convey the idea of repeating some action until certain condition is met.
Second, if all your functions are doing the same operation on different sets of data, then you'd better convert them to a class with a method:
struct MyClass
{
void function()
{
for (;;)
{
int a;
std::cin >> a;
switch (a)
{
case 1:
m_a = m_a + 10000;
m_b = m_b + 100;
continue;
case 0:
m_b = m_b + 100;
continue;
}
m_c = m_a / m_b;
break;
}
}
int m_a = 0; // Requires C++11
int m_b = 0;
int m_c = 0;
};
MyClass b1;
MyClass b2;
// ...
MyClass b8;
int main()
{
b1.function();
b2.function();
// Use `b1.m_c` through `b8.m_c` here
return 0;
}
Third, if you don't need those m_a
, m_b
and m_c
values after the functions have completed their work, you may convert m_a
and m_b
into local variables, convert m_c
into a function return value, and get rid of the class:
int function()
{
int a = 0;
int b = 0;
for (;;)
{
int x;
std::cin >> x;
switch (x)
{
case 1:
a = a + 10000;
b = b + 100;
continue;
case 0:
b = b + 100;
continue;
default:
return a / b;
}
}
}
int main()
{
int c1 = function();
int c2 = function();
// ....
int c8 = function();
// Use `c1` through `c8` here
return 0;
}
Upvotes: 1
Reputation: 31464
The easiest way would probably be to use a std::function as an argument. But you could also use a plain function pointer or a pointer to member function if that's a better match for your use case.
Upvotes: 2