functions vs not functions

How functions make your program cleaner?
1
2
3
4
5
6
7
8
 Int argument(int x,int y)
{
 return x+y;
}                                       int main
{
int result=arg(1,2); 
cout<<result;
}

I think its way cleaner without using function
1
2
3
Int main
{ int x=1,y=2;
Cout<<x+y;}

see?
That is true, but if you want to change X or Y? Maybe you want user input or the values will dynamically change during a certain time. We don't know the purpose for making your code but calling functions is crucial in C++ as you will use it in almost any program.
closed account (z05DSL3A)
1
2
3
4
5
6
7
#include <iostream>

int main()
{
    int x = 1, y = 2;
    std::cout << x + y;
}

Has lots of function calls, you just don't see them yet.
Last edited on by Canis lupus
The example x + y is relatively trivial and the function plays no useful role there. But say you needed to to something more complicated, such as calculate the average, or maybe the root mean square value of a list of numbers. Here the calculation may be more complicated, and simply clutters up the body of main(). It also means the function can be tested and debugged, and then simply used over and over, without the need to repeatedly write the same code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cmath>

    using namespace std;

// calculate root mean square value of four numbers
double rms(double a, double b, double c, double d)
{
    double sumsq = a*a + b*b + c*c + d*d;
    return sqrt( sumsq / 4.0);
}

int main()
{
     cout << rms(1, 3, 5, 7) << endl;
     cout << rms(16, 15.5, 11.6, 18.1) << endl;

    return 0;
}


Also, with the use of sensible naming of a function, it makes the code more readable, as the meaning can be understood without having to analyse the intricate details of the code.
Your example is too trivial. To claim that functions are useless based on that is like claiming that cars are useless because it takes you 30 seconds to get to your neighbour, but it takes 5 minutes by car.

Functions are useful because
a) They allow for code reuse and decrease code duplication.
b) They are making code easier to read: instead of trying to make sense of algorithm used, you can just look at function name and understand what it does — invert(matrix) vs monstruosity which underlying algorithm is (even worse if you do not use other functions like det() and transpose() inside)
c) They hides irrelevant detail of implementation from user, allowing to concentrate on problem on hand.
d) Code with functions can be more effective and fast..
e) It is easier to debug
f) Recursive calling is possible only within functions
Hello lupus I see it call a lot of function but that's not the point
Topic archived. No new replies allowed.