| View previous topic :: View next topic |
| Author |
Message |
C-Dizzle Grandmaster Cheater
Reputation: 89
Joined: 16 Mar 2008 Posts: 623
|
Posted: Wed Aug 17, 2011 9:24 am Post subject: Slowly learning C++, need some advice. |
|
|
So, I was set the task to make something that would double a number. I came up with:
| Code: | #include "stdafx.h"
#include <iostream>
int main()
{
using namespace std;
int x;
cout << "Double: ";
cin >> x;
cout << 2 * x << endl;
return 0;
} |
I looked at the solution and they used;
| Code: | #include <iostream>
int doubleNumber(int x)
{
return 2 * x;
}
int main()
{
using namespace std;
int x;
cin >> x;
cout << doubleNumber(x) << endl;
return 0;
}
// The following is an alternate way of doing main:
int main()
{
using namespace std;
int x;
cin >> x;
x = doubleNumber(x);
cout << x << endl;
return 0;
} |
So my question is - Is mine written badly?
|
|
| Back to top |
|
 |
SwaggaJackin' Master Cheater
Reputation: 2
Joined: 06 Nov 2009 Posts: 304
|
Posted: Wed Aug 17, 2011 9:49 am Post subject: |
|
|
| What you did was fine, but probably considered sloppy. In their example they made a separate function for doubling the number. The reason for this is probably because they want to set the practice of creating functions to do tasks so you can reuse them in other areas, rather than writing one giant function with everything in it.
|
|
| Back to top |
|
 |
atom0s Moderator
Reputation: 205
Joined: 25 Jan 2006 Posts: 8587 Location: 127.0.0.1
|
Posted: Wed Aug 17, 2011 11:23 am Post subject: |
|
|
It's not wrong, but its less 'portable' and harder to maintain if you needed to go in and change things; like if you wanted to change it to *3 or something on those lines. While in a few line project like that its easy, in a large scale project its easier to maintain functional code rather then code that is inlined like that.
Think of it as if there were multiple calls to the same thing, if you did x * 2 like 50 times in a large scale project, its easier to maintain changes inside a function rather then having to go and change each individual line.
_________________
- Retired. |
|
| Back to top |
|
 |
C-Dizzle Grandmaster Cheater
Reputation: 89
Joined: 16 Mar 2008 Posts: 623
|
Posted: Wed Aug 17, 2011 1:19 pm Post subject: |
|
|
| Ahh, thanks for clearing that up guys, it's appreciated.
|
|
| Back to top |
|
 |
|