Tuesday, September 4, 2012

Trying and Testing Code In C Programming

Getting to grips with C can be a daunting task and the initial outlay for a C compiler, In Circuit Emulator and necessary hardware for the PIC can be prohibitive at the evaluation stage of a project. The C compiler supplied on this disk was obtained from the Internet and is included as a test bed for code learning. Basic code examples and functions can be tried, tested and viewed before delving into PIC specific C compilers which handle I/O etc.

C Coding Standards
Program writing is like building a house – if the foundations are firm, the rest of the code will stack up. If the foundations are weak, the code will fall over at some point or other. The following recommendations were taken from a C++ Standards document and have been adapted for the PIC.

Names – make them fit their function Names are the heart of programming so make a name appropriate to its function and what it’s used for in the program. Use mixed case names to improve the readability

ErrorCheck is easier than ERRORCHECK
Prefix names with a lowercase letter of their type, again to improve readability:

g Global gLog;
r Reference rStatus();
s Static sValueIn;
Braces{}
Braces or curly brackets can be used in the traditional UNIX way
if (condition) {
…………….
}
or the preferred method which is easier to read
if (condition)
{
…………….
}


Tabs and Indentation
Use spaces in place of tabs as the normal tab setting of 8 soon uses up the page width. Indent text only as needed to make the software readable. Also, tabs set in one editor may not be the same settings in another – make the code portable.
Line Length
Keep line lengths to 78 characters for compatibility between monitors and
printers.
Else If Formatting
Include an extra Else statement to catch any conditions not covered by the
preceding if’s

if (condition)
{}
else if (condition)
{}
else
{
……….. /* catches anything else not covered above */
}

Condition Format in C Programming

Where the compiler allows it, always put the constant on the left hand side of an equality / inequality comparison, If one = is omitted, the compiler will find the error for you. The value is also placed in a prominent place.
if ( 6 == ErrorNum) …
Initialize All Variables
Set all variables to a known values to prevent ‘floating or random conditions’
int a=6, b=0;

Comments in C Programming

Comments create the other half of the story you are writing. You know how your program operates today but in two weeks or two years will you remember, or could someone else follow your program as it stands today? Use comments to mark areas where further work needs to be done, errors to be debugged or future enhancements to the product.

No comments:

Post a Comment