How we change what others think, feel, believe and do
CHAPTER 9 : Data Usage
C has a very rich and flexible declaration system, enabling many ways of declaring the same item. In declaring items, there are two main approaches, based on the principles of simplicity and explicitness, which are applied to the types and specifiers used:
The 'simple' approach
The simple approach to choosing a variable type is to select the first sufficient type from a priority list of types. Typically, int is first in the list - this means that short and char will never be used for integers as an int will always suffice where they might be used. Specifiers are only used when they are necessary. Thus auto will never be used, and unsigned will only be used when it is necessary. The simple approach is reflected in the declaration style:
This approach makes types easier to choose and declarations less cluttered. It may also result in simpler expressions where less casting is required and where there may be less confusion over type. However, the intent of the variable is less clear, and it is possible that errors of omission may occur.
The 'explicit' approach
The explicit approach to choosing a variable is to select the type that is closest to the intent of the variable. Thus an 'unsigned char' would be used for a number which will only hold values between 0 and 16. This approach makes the intent of the variable clear, but may result in more cluttered declarations and expressions:
auto unsigned int WordLen;
The compromise approach
A sensible compromise is to take a balanced view. Thus: auto is so uncommon it may safely be dropped; int, as the most efficient variable, is used for most common situations; short and char are useful where space is at a premium (for example in arrays); long is used where the size of the variable is large or uncertain; unsigned is used in abnormal situations where not using it could cause problems (for example for bit variables). Some of these decisions can be circumvented by typedef'ing common types (see 9.3). The declaration example would now be:
unsigned int WordLen;
9.1.1 Declarations in inner blocks
It is minimizing scope and being explicit to declare variables in a block that are used only within that block, rather than at the start of the function:
The arguments for and against this are similar to those about whether to put the context for the function (extern's, etc.) at the start of the function or at the start of file (see 7.3.1). It is probably more common to separate data and code, defining all local variables at the start of the function. Either way, it is worth being clear about the chosen approach.
And the big