Here in this post I am discussing a few points to note while writing C/C++ programs. These points might help you reduce errors while writing programs and also makes them easy to debug.
- Be careful while using the == (Relational Operator) and = (Assignment) operators. So many errors were made because of these two operators. Consider the code given below. It will not show any error.
printf("\nHello");
}
The actual code intended was the one given below.
if(x=1)
{
printf("\nHello");
}
But if you change the code as follows, it will show an error if you forget an equal to sign.
if(1==x)
{
printf("\nHello");
}
Here if you forget an equal to sign, you will get the following error "lvalue required".
- Always use ++ and -- operators on lines by themselves. Avoid statements like arr[++i] as you may not get the intended side effect.
- Try to have a default statement in every switch statement, even if it is not doing anything.
- Put parentheses around each constant expression defined by the pre-processor #define directive.
EQN(5+6) will give you 41 output instead of the intended 121.
The correct statement is shown below.
#define EQN(x,y) (x)*(y)- Never do nothing silently. For example consider the code given below. It was included in the program to bring some delay.
A better code is shown below.
for(i=0;i<10000;i++)
/* Do Nothing, Just for Delay */ ;
This will make debugging easier at a later stage.
- The upper & lower limit of data types in C/C++ is often dependent on the compiler. To verify the limits of data types in your compiler check the header file limits.h.
- Beware of Semi Colons in your program.
- If statements in your program contains operators with different precedence, then using brackets is a very good idea.
No comments:
Post a Comment