Jump to: navigation, search

Disclaimer of incompleteness

This article is skeletal and far from complete - it's in the process of being fleshed out and at this point contains imbalances.

Introduction

Style refers to the way that code is written, as opposed to what it does. There are many components to style, including at the basic level indentation, whitespace and brace placement; beyond that are such issues as when, why and how to comment, naming conventions for functions, macros and variables, whether goto is allowed (and if so, when) and whether multiple return statements are permitted in a function. Other less basic issues include how and when debugging code should be inserted and enabled/disabled. Some style issues border onto the realm of code and software design - for example: how the internationalisation of user-visible messages is to be achieved.

Choice of elements of style is often arbitrary, on the other hand there are also often good reasons to prefer one choice over another. The rest of this page discusses some common elements of style and the pros and cons of various alternatives.

For the guidelines that apply to this wiki in particular, see Project:Code style guidelines.

Elements of style

Function conventions

Multiple exit points

The multiple exit point style element concerns whether it's allowable for more than one exit point (i.e. a return statement or a call to exit()) to exist per function.

Pros of multiple exit points
  • they can reduce the complexity and size of the source code
Cons of multiple exit points
  • it can be easy to miss the earlier return statement and misread a function's behaviour
  • it can be equated to a goto statement (i.e. "goto end-of-function") and the same arguments against unstructured code can be applied
Possible choices
  • a blanket ban on multiple exit points
  • a blanket allowance
  • discourage multiple exit points, though allow considerate usage where appropriate (quite easy to miss on that account)
  • ban multiple exit points for all but very short functions (say, 10 lines or less)
  • ban multiple exit points unless they occur within the branches of an if-else chain and there is no exit point outside that chain
  • ban multiple exit points unless the final one has an accompanying comment that other prior exit points exist.

goto statements

Basically the same justifications and pitfalls apply to goto statements as to multiple exit points. While they can be used in well designed and structured code to improve readability and conciseness, they should be avoided where there's no huge obvious gain.

Existing style guidelines

The main four

The styles below represent the main four bracing style variations in C, although at least the first two define more than just bracing style:

  • "K&R" style - that used in "The C Programming Language" by Kernighan and Ritchie.
  • GNU Style
  • Allman (or BSD) style
  • Whitesmiths style.

Others

References

Personal tools