Skip to content
OlegHahm edited this page Mar 29, 2013 · 35 revisions

Coding Conventions

General

  • Avoid dynamic memory allocation (malloc/free, new etc.)! It will break real-time guarantees, increase code complexity, and make it more likely to use more memory than what is available.
  • Line length: aim for not more than 80 characters per line, the absolute maximum should be at 100 characters per line.

Types

  • Be careful with platform depending type sizes like int or long. Use data types that includes the bit length in the name like uint16_t when you need to make sure that a certain variable has exactly this length.
  • A type definition (using typedef) always ends with a "_t".
  • If typedefs are used for structs, it has to be specified at the struct definition (i.e., not as a separate line). E.g. like this:
     typedef struct {
        uint8_t a;
        uint8_t b;
    } foobar_t;

Variables

  • Do NOT use global variables unless there is no way to avoid it.
  • If you declare a variable within a header file, you MUST use the keyword extern.

Functions

  • Every functions needs a prototype - additional to its definition. If a prototype is specified within a c-File it has to be declared BEFORE any function definition.
  • If the scope of a function is limited to one file, it MUST be declared as static.
  • Functions without parameters must be specified with void, e.g. xxx(void).
  • Keep functions short! As a rule of thumb, the function's body should not exceed one screen.
  • Do NOT use global macros defining more than one line of code. Use inline functions instead.

Return values

  • Any function must return one of the following values:
  • logical value (zero or not zero)
  • an error code (given as a negative number or zero) or a positive status value
  • the count of read or written bytes/values for I/O functions
  • the position or address (for search functions)
  • a pointer
  • NULL indicates an error case, too.
  • Do NOT return a struct or any bigger value! They would get copied to the stack, resulting in expensive operations. Moreover, some compilers have trouble with larger return values. Use pointer to structs instead, but pay attention to the lifetime of the struct.
  • If possible, prefer int over uint, in order to add error codes later on.

Clone this wiki locally