Style Rules and Common Errors
TODO: write this appendix...
Good programming practice tends to come with experience - abide by basic rules - apply them consistently - make code clean, modular, and easy to read and maintain
Small scale organisation: - clean consistent formatting, naming conventions - comments - grouping of related operations, spacing (paragraphs) - conciseness: never write a long program when a short one will do. Code can be verbose and waffley just like written English. - functions: names and interfaces
Large scale organisation: - modularity - private, public interfaces
Collected Style rules: - indentation 1.3 - comments 1.4 - key to indentation and naming: consistency - naming - variables 1.5, 2.1 - symbolic constants 1.5, 2.4, 10.2 - structs 11.1 - precedence 2.8 - switch 3.3 - do-while 3.5 - magic numbers 4.4 - external variables 5.2 - pointer syntax 7.2 - pointer efficiency 7.5 - argv, argc 13.4 - headers 14.2.2
- when comparing floats, avoid ==, use ¡= or =¿ (due to roundoff error)
- (void) cast to ignore function return value - code duplication is an error
Wrapper functions, used for: - type-safe interfaces with generic code - adapt mismatched interfaces - group set of functions (and other operations) in a particular sequence
Design: - design at a component level, build up a reusable toolbox as well as application specific components. - design for the general case. rather than solving a specific problem, try to generalise. This often results in a more elegant, often simpler solution, and promotes reuse. - build components out of other components. Layered design. Lowest layer is platform wrappers. - use adapter functions to use components with non matching interfaces.
Writing portable code: - avoid bitfields - use the standard library - avoid casts and unnecessarily low-level coding - separate platform specific code from standard conforming code, place in separate modules, give a portable public interface - prefer cross-platform libraries, eg, GUI libraries
Errors: - NUL is not NULL - dangling else - scanf needs pointer: & - assert is a macro, so don’t put necessary code in it - break from if statement - use of error or abort - numerical - divide-by-zero - overflow