(11-10-2009, 11:16 PM)nevets04 Wrote:Code:int addition (int a,int b)
{
int r;
r=a+b;
return(r);
}
Just a few points I will make about this which are good habits to get into.
1) Pass parameters that aren't going to be changed in the function as "const", pass complex data types (such as classes, structs, etc) as a const reference (or const pointer if you really must). The "const" part of this will allow the compiler to optimise better since you are telling it that this parameter won't be changed, the reference/pointer part will save copying the complex type (which pass by value would have done).
Example:
Code:
int addition(const int a, const int b)
{
int r;
r=a+b;
return(r);
}
And for a complex data type:
Code:
int printLine(const std::string &str)
{
std::cout << str << std::endl;
}
2) You creating a temporary variable (which is using it's default constructor), you are then assigning to that variable (using the assignment operator), before returning by value (which will take yet another copy). All in all that int is having it's value set twice, and copied once; this can be done cheaper.
Firstly, you could always use the copy-constructor of the int. (Be careful of this when using complex data types as the copy-constructor might not have been defined properly). This will save the initial defaulting of the value:
Code:
int addition(const int a, const int b)
{
int r(a + b);
return(r);
}
However you are still creating a temporary instance of the int to just return it by value, so the most optimal way would be to just return the sum of the two numbers:
Code:
int addition(const int a, const int b)
{
return a + b;
}
These are trivial points for such a small application, but for larger applications which are performance critical they all start to add up. You might want to read GotW.
The little boat gently drifted across the pond exactly the way a bowling ball wouldn't.