### Feed back on using Functions

I want to get some feedback on your thoughts about passing values to a function that don't really "calculate" or are not "calculated" into the rest of the function. I'm referring to passing a variable into a function for the sole purpose to make the function run a particular code segment.

For example, the following code is one function that can return an array's ndx location.

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253`` `````` int main() { const char small = 's'; const char large = 'l'; int size = 0; cin >> size; value_Large_or_Small(size, small) //using char small value_Large_or_Small(size, large) //using char large return 0; } int value_Large_or_Small(int size, char n) //n chooses case s or l { int ndx = 0; int Small = pnt[0]; int Large = pnt[0]; switch(n) { case 's': for(int i = 0; i < size; i++) //if n is s if(Small > pnt[i]) { Small = pnt[i]; ndx = i; } break; case 'l': for(int i = 0; i < size; i++) //if n is l if(Large < pnt[i]) { Large = pnt[i]; ndx = i; } } return ndx; }``````

this function will return the index number to the largest value or the smallest value in an array (example myArra[ndx]).
this is determined by either choosing the small or large char variable.

so is this acceptable or is it better to write two separate functions that find the largest value and one that finds the lowest value.

ok, second example:

there is a game that flips 3 coins. If your flips total \$1.00 you win. It doesn't matter the number of flips as long as you don't go over (like playing blackjack).

 ``1234567891011121314151617181920212223242526272829`` `````` int main() { int Win = 0; int Lose = 0; int cnt = 0; cnt = (some function that return 1 or 0); WIN_LOSE_COUNT(cnt, Win, Lose); // win and lose using pass by reference cout << Win << endl; cout << Lose << endl; return 0; } void WIN_LOSE_COUNT(int cnt, int &W, int &L) // cnt is eaither 1 or 0 { if(cnt == 1) W++; else if(cnt == 0) L++; }``````

Here I am just using the variable cnt that is returning either 1 or 0 to count W and L.
would this be an acceptable function to count wins and losses, or is it better to count the wins and losses in the function that actually does the calculation.

both of these functions work and they get the job done, I am just inquiring if this is considered a "bad" habit in programming.

Last edited on
Hi,

Consider writing the functions using a `bool` argument. That way you could write half as much code in 1 function :+) - For the first function anyway.

For the second snippet, I would pass a variable by reference and use it to count the wins/losses in the function that does the calculation.

Also consider using an STL container like std::vector rather than ordinary arrays. Then investigate the range based for loop.

Good Luck !!
Topic archived. No new replies allowed.