(C++) purpose of using functions
February 24, 2017 · View on GitHub
(C++) purpose of using functions
Possible purposes of using functions are (incomplete list):
- Avoid code duplication
- Improving the readability of your code
- Decrease scope bloat
- Increasing const-correctness
Below is an example that asks the user for two values and calculates whether these and the sum of these values are prime. The first piece of code does not use functions, the second does. In comment is shown which of the four purposes are served.
Example without functions
#include <cmath> #include <iostream> //code has twice as many lines! //Less clear what main() does int main() { int value1 = -1; //value1 cannot be const //value1 must be at main() scope to be summed (scope bloat) int value2 = -1; //value2 cannot be const //value2 must be at a main() scope to be summed (scope bloat) { //This code is copied three times and modified //Unclear what the code fragment does std::cin >> value1; bool isPrime = true; //Extra variable needed const int max = static_cast<int>(std::sqrt(static_cast<double>(value1))) + 1; for(int i=2; i!=max; ++i) { if (value1 % i == 0) { isPrime = false; break; } } std::cout << "Value1 is " << (isPrime ? "" : "not ") << "prime\n"; } { //This code is copied three times and modified //Unclear what the code fragment does std::cin >> value2; bool isPrime = true; //Extra variable needed const int max = static_cast<int>(std::sqrt(static_cast<double>(value2))) + 1; for(int i=2; i!=max; ++i) { if (value2 % i == 0) { isPrime = false; break; } } std::cout << "Value2 is " << (isPrime ? "" : "not ") << "prime"; } { //This code is copied three times and modified //Unclear what the code fragment does const int valueSum = value1 + value2; bool isPrime = true; //Extra variable needed const int max = static_cast<int>(std::sqrt(static_cast<double>(valueSum))) + 1; for(int i=2; i!=max; ++i) { if(valueSum % i == 0) { isPrime = false; break; } } std::cout << "Value1 + value2 is " << (isPrime ? "" : "not ") << "prime\n"; } }
Example with functions
#include <cmath> #include <iostream> //From http://www.richelbilderbeek.nl/CppIsPrime.htm //Clear what the code fragment does bool IsPrime(const int x) { const int max = static_cast<int>(std::sqrt(static_cast<double>(x))) + 1; for(int i=2; i!=max; ++i) { if(x % i == 0) return false; } return true; } //Clear what the code fragment does int AskUserInput() { int x; //Temporary variable 'x' as local as possible std::cin >> x; return x; } //code has twice as few lines! //Clear(er) what main() does int main() { const int value1 = AskUserInput(); //value1 is const const int value2 = AskUserInput(); //value2 is const std::cout << "Value1 is " << (IsPrime(value1) ? "" : "not ") << "prime\n"; std::cout << "Value2 is " << (IsPrime(value2) ? "" : "not ") << "prime\n"; std::cout << "Value1 + value2 is " << (IsPrime(value1 + value2) ? "" : "not ") << "prime\n"; }