5 Tips for a less buggy C code
5 Tips for a less buggy C code
1. when comparing a variable to a value in if statement ,always make the value at left-hand side . Normally ,by mistake if assignment operator (=) is used instead of equal operator (==) in a comparison , This won’t generate any compilation error but it will generate a logical error . By placing the value at left-hand side , if assignment operator is used by mistake instead of equal operator , a compilation error will be generated.
2. Never use pointers to decode a message containing more than one signal .This way leads to platform dependant code and reduce code reusability . for example If you have a message consisting of 2 bytes the first byte represents temperature value and the second value represents humidity value .Casting address of the message to a pointer to character to read each signal will generate different result on different endianness systems .At this case it is more safe to use shift operators to read each signal .
3. Using right shift operator with signed negative variable will fill most significant bit with one not zero like any other case using shift operators.
4. When writing a function and its input is void its prototype should be written like this [return type function_name (void)] not like that [return type function_name ()] .if parameters are passed to a function with void input and last pattern of prototype is used . it is compiler dependant but if first pattern of prototype is used it will generate compilation error.
5. State machine states should be defined using enum not preprocessor directive (# define ) as enum prevents redeclaration of states and generates compilation error but using preprocessor directive (# define ) can lead to state redeclaration ,also if there are great number of states using (#define )) may lead to more than one state with the same value which will generate logical error.
Comments
Post a Comment