Hey I have been programming for a little while and I am getting used to c++ and I was wondering if there were any good habits to get into while starting off. I know the basics like comments and stuff so people know what is happening. Is there any good ones out there that could make my programs more readable or even more efficient(I know I'll learn this advanced stuff but any easy more efficient stuff). Thanks for helping the forum is great!
Prefer standard library over reinventing the wheel again.
Prefer C++ features over C ones.
Get rid of manual memory management.
Reduce number of dependences in your code.
Avoid code duplication.
1) It is easier to read int x = isThisTheRightOne() ? theFirstPossibleValue : theSecondPossibleValue;
than int x=isThisTheRightOne()?theFirstPossibleValue:theSecondPossibleValue;
2) Proper indentation makes code so much easier to understand than poorly indented code.
3) A blank line between sections of code (as well as comments) make it easier to understand what each section is doing.
Along the lines of avoiding code duplication, avoid intent duplication.
For example, think of a class Tree, which has an amount of class Leaf. Some instance methods might go like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Tree
{
std::vector< Leaf > m_leaves;
void looping_function( void )
{
for ( int i = 0; i < m_leaves.size() ; ++i )
// do something
}
void another_looping_function( void )
{
for ( int i = 0; i < m_leaves.size() ; ++i )
// do something
}
};
The intent duplication going on here is that we do something based on the amount of Leaves. It is more understandable and easier to maintain if you express that intent as a function:
class Tree
{
std::vector< Leaf > m_leaves;
int amount_of_leaves( void ) // actually, instead of int: std::vector< Leaf >::size_type
{
return m_leaves.size();
}
void looping_function( void )
{
for ( int i = 0; i < amount_of_leaves() ; ++i )
// do something
}
void another_looping_function( void )
{
for ( int i = 0; i < amount_of_leaves() ; ++i )
// do something
}
};
Is there any good ones out there that could make my programs more readable or even more efficient
Look for patterns.
Example #1:
If you have 4 or more variables with the same name, consider using an array of the variables: int t1, t2, t3, t4, t5;
Possible solution: int t[5];//int array, of 5 elements.
Example #2:
If you are printing nearly identical data, consider a recursive approach:
1 2 3 4 5
cout<<"The element in argument 1 is: "<< t1<<endl;
cout<<"The element @ 1 is: "<< t2<<endl;
cout<<"The element @ 2 is: "<< t3<<endl;
cout<<"The element @ 3 is: "<< t4<<endl;
cout<<"The element @ 4 is: "<< t5<<endl;
Possible solution:
1 2 3 4
for(int i=0;i<5;++i)
{
cout<<"The element @ "<<i+1<<" is: "<<t[i]<<endl;
}