C Programming Code Conventions for ECE 4436 & 4437, Study notes of Microprocessors

Coding conventions for c programs in the context of electrical and computer engineering courses 4436 and 4437. It covers topics such as line length, comments, indentation, compound statements, control structures, and variable naming. The document aims to improve code readability and maintainability.

Typology: Study notes

Pre 2010

Uploaded on 08/19/2009

koofers-user-klv
koofers-user-klv 🇺🇸

9 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
v2
C Code Conventions for ECE 4436 & 4437
(adapted from Code Conventions for the Java Programming Language,
http://java.sun.com/docs/codeconv/ )
1 - Introduction
1.1 Why Have Code Conventions
Code conventions are important to programmers for a number of reasons:
80% of the lifetime cost of a piece of software goes to maintenance.
Hardly any software is maintained for its whole life by the original author.
Code conventions improve the readability of the software, allowing engineers to
understand new code more quickly and thoroughly.
If you ship your source code as a product, you need to make sure it is as well
packaged and clean as any other product you create.
4 - Indentation
Four spaces should be used as the unit of indentation.
4.1 Line Length
Avoid lines longer than 80 characters, since they're not handled well by many terminals
and tools.
Note: Examples for use in documentation should have a shorter line length – generally no
more than 70 characters.
4.2 Wrapping Lines
When an expression will not fit on a single line, break it according to these general
principles:
Break after a comma.
Break before an operator.
Prefer higher-level breaks to lower-level breaks.
Align the new line with the beginning of the expression at the same level on the
previous line.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download C Programming Code Conventions for ECE 4436 & 4437 and more Study notes Microprocessors in PDF only on Docsity!

C Code Conventions for ECE 4436 & 4437

(adapted from Code Conventions for the Java Programming Language ,

http://java.sun.com/docs/codeconv/ )

1 - Introduction

1.1 Why Have Code Conventions

Code conventions are important to programmers for a number of reasons:

  • 80% of the lifetime cost of a piece of software goes to maintenance.
  • Hardly any software is maintained for its whole life by the original author.
  • Code conventions improve the readability of the software, allowing engineers to

understand new code more quickly and thoroughly.

  • If you ship your source code as a product, you need to make sure it is as well

packaged and clean as any other product you create.

4 - Indentation

Four spaces should be used as the unit of indentation.

4.1 Line Length

Avoid lines longer than 80 characters, since they're not handled well by many terminals

and tools.

Note: Examples for use in documentation should have a shorter line length – generally no

more than 70 characters.

4.2 Wrapping Lines

When an expression will not fit on a single line, break it according to these general

principles:

  • Break after a comma.
  • Break before an operator.
  • Prefer higher-level breaks to lower-level breaks.
  • Align the new line with the beginning of the expression at the same level on the

previous line.

  • If the above rules lead to confusing code or to code that's squished up against the

right margin, just indent 8 spaces instead.

Here are some examples of breaking function calls:

someFunction(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5);

var = someFunction(longExpression1, someFunction2(longExpression2, longExpression3));

Following are two examples of breaking an arithmetic expression. The first is preferred,

since the break occurs outside the parenthesized expression, which is at a higher level.

longName1 = longName2 * (longName3 + longName4 - longName5)

  • 4 * longname6; // PREFER

longName1 = longName2 * (longName3 + longName

  • longName5) + 4 * longname6; // AVOID

Following are two examples of indenting function declarations. The first is the

conventional case. The second would shift the second and third lines to the far right if it

used conventional indentation, so instead it indents only 8 spaces.

//CONVENTIONAL INDENTATION

someFunction(int anArg, int anotherArg, float yetAnotherArg, double andStillAnother) { ... }

//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS static void horkingLongFunctionName(int anArg, int anotherArg, float yetAnotherArg, double andStillAnother) { ... }

Line wrapping for if statements should generally use the 8-space rule, since

conventional (4 space) indentation makes seeing the body difficult. For example:

//DON'T USE THIS INDENTATION

if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { //BAD WRAPS doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS }

//USE THIS INDENTATION INSTEAD if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt();

5.1.1 Block Comments

Block comments are used to provide descriptions of files, functions, data structures and

algorithms. Block comments may be used at the beginning of each file and before each

function. They can also be used in other places, such as within functions. Block

comments inside a function should be indented to the same level as the code they

describe.

A block comment should be preceded by a blank line to set it apart from the rest of the

code.

  • Here is a block comment. */

5.1.2 Single-Line Comments

Short comments can appear on a single line indented to the level of the code that follows.

If a comment can't be written in a single line, it should follow the block comment format.

A single-line comment should be preceded by a blank line. Here's an example of a single-

line comment:

if (condition) {

/* Handle the condition. */ ... }

5.1.3 Trailing Comments

Very short comments can appear on the same line as the code they describe, but should

be shifted far enough to separate them from the statements. If more than one short

comment appears in a chunk of code, they should all be indented to the same tab setting.

Here's an example of a trailing comment in C code:

if (a == 2) { return TRUE; /* special case / } else { return isPrime(a); / works only for odd a */ }

5.1.4 End-Of-Line Comments

The // comment delimiter can comment out a complete line or only a partial line. It

shouldn't be used on consecutive multiple lines for text comments; however, it can be

used in consecutive multiple lines for commenting out sections of code. Examples of all

three styles follow:

if (foo > 1) {

// Do a double-flip. ... } else { return false; // Explain why here. } //if (bar > 1) { // // // Do a triple-flip. // ... //} //else { // return false; //}

7 - Statements

7.1 Simple Statements

Each line should contain at most one statement. Example:

argv++; // Correct argc--; // Correct argv++; argc--; // AVOID!

7.2 Compound Statements

Compound statements are statements that contain lists of statements enclosed in braces "{

statements }". See the following sections for examples.

  • The enclosed statements should be indented one more level than the compound

statement.

  • The opening brace should be at the end of the line that begins the compound

statement; the closing brace should begin a line and be indented to the beginning

of the compound statement.

  • Braces are used around all statements, even single statements, when they are part

of a control structure, such as a if-else or for statement. This makes it easier to

add statements without accidentally introducing bugs due to forgetting to add

braces.

for ( initialization ; condition ; update );

When using the comma operator in the initialization or update clause of a for statement,

avoid the complexity of using more than three variables. If needed, use separate

statements before the for loop (for the initialization clause) or at the end of the loop (for

the update clause).

7.6 while Statements

A while statement should have the following form:

while ( condition ) { statements ; }

An empty while statement should have the following form:

while ( condition );

7.7 do-while Statements

A do-while statement should have the following form:

do { statements ; } while ( condition );

7.8 switch Statements

A switch statement should have the following form:

switch ( condition ) { case ABC: statements ; /* falls through */

case DEF: statements ; break;

case XYZ: statements ; break;

default: statements ; break; }

Every time a case falls through (doesn't include a break statement), add a comment

where the break statement would normally be. This is shown in the preceding code

example with the /* falls through */ comment.

Every switch statement should include a default case. The break in the default case is

redundant, but it prevents a fall-through error if later another case is added.

8 - White Space

8.1 Blank Lines

Blank lines improve readability by setting off sections of code that are logically related.

Two blank lines should always be used in the following circumstances:

  • Between sections of a source file

One blank line should always be used in the following circumstances:

  • Between functions
  • Between the local variables in a function and its first statement
  • Before a block or single-line comment
  • Between logical sections inside a function to improve readability

8.2 Blank Spaces

Blank spaces should be used in the following circumstances:

  • A keyword followed by a parenthesis should be separated by a space. Example:

while (true) { ... }

Note that a blank space should not be used between a function name and its

opening parenthesis. This helps to distinguish keywords from function calls.

  • A blank space should appear after commas in argument lists.
  • All binary operators except. should be separated from their operands by spaces.

Blank spaces should never separate unary operators such as unary minus,

increment ("++"), and decrement ("--") from their operands. Example:

allowed.

Variable names should be short yet meaningful. The

choice of a variable name should be mnemonic- that

is, designed to indicate to the casual observer the

intent of its use. One-character variable names

should be avoided except for temporary

"throwaway" variables. Common names for

temporary variables are i, j, k, m, and n for

integers; c, d, and e for characters.

Constants

The names of variables declared constants and of

ANSI constants should be all uppercase with words

separated by underscores ("_"). (ANSI constants

should be avoided, for ease of debugging.)

static int

MIN_WIDTH = 4;

static int

MAX_WIDTH =

static int

GET_THE_CPU =

10 - Programming Practices

10.1 Providing Access to Variables in a Module

Don't make any variable global without good reason. Often, variables don't need to be

explicitly set or gotten - often that happens as a side effect of function calls.

10.3 Constants

Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which

can appear in a for loop as counter values.

10.4 Variable Assignments

Avoid assigning several variables to the same value in a single statement. It is hard to

read. Example:

fooBar.fChar = barFoo.lchar = 'c'; // AVOID!

Do not use the assignment operator in a place where it can be easily confused with the

equality operator. Example:

if (c++ = d++) { // AVOID! ... }

should be written as

if ((c++ = d++) != 0) { ... }

Do not use embedded assignments in an attempt to improve run-time performance. This

is the job of the compiler. Example:

d = (a = b + c) + r; // AVOID!

should be written as

a = b + c; d = a + r;

10.5 Miscellaneous Practices

10.5.1 Parentheses

It is generally a good idea to use parentheses liberally in expressions involving mixed

operators to avoid operator precedence problems. Even if the operator precedence seems

clear to you, it might not be to others-you shouldn't assume that other programmers know

precedence as well as you do.

if (a == b && c == d) // AVOID! if ((a == b) && (c == d)) // RIGHT

10.5.2 Returning Values

Try to make the structure of your program match the intent. Example:

if ( booleanExpression ) { return true; } else { return false; }

should instead be written as

return booleanExpression ;