Wednesday, 16 January 2013

Some Tips for Writing C/C++ Programs

  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.                              

                      The actual code intended was the one given below.
                      But if you change the code as follows, it will show an error if you forget an equal to sign.
                      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.
                              #define EQN(x,y)  x*y 
                       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.
                              for(i=0;i<10000;i++) ; // Note the semi colon.                         
                        A better code is shown below.
                               /* 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