-

Stylistic Considerations

From HI-TECH C for CP/M Fan WIKI(EN)
Jump to: navigation, search

Although it is not the purpose of this manual to set out a coding standard for C, some comments regarding use of some of the features of HI-TECH C may be useful.

Member Names

Although HI-TECH C allows the same structure or union member name to be used in more than one structure or union, this may not be allowed by another C compiler. To help ensure portability of the code, it is recommended that member names all be distinct, and a useful way of ensuring this is to prefix each member name with one or two letters derived from the name of the structure itself. An example is given in fig. 7.

struct tree_node
{
struct tree_node * t_left;
struct tree_node * t_right;
short t_operator;
};


Fig. 7. Member Naming


Because HI-TECH C insists on use of all intermediate names when referencing a member nested inside several structures, some simple macro definitions can serve as a short- hand. An example is given in fig. 8.

struct tree_node
{
short t_operator;
union
{
struct tree_node * t_un_sub[2];
char * t_un_name;
long t_un_val;
} t_un;
};

#define t_left t_un.t_un_sub[0]
#define t_right t_un.t_un_sub[1]
#define t_name t_un.t_un_name
#define t_val t_un.t_un_val


Fig. 8. Member Name Shorthand


This enables the variant components of the structure to be referred to by short names, while guaranteeing portability and presenting a clean definition of the structure.

Use of Int

It is recommended that the type int be avoided wherever possible, in preference to the types short or long. This is because of the variable size of int, whereas short is commonly 16 bits and long 32 bits in most C implementations.

Extern Declarations

Some compilers permit a non-initialized global variable to be declared in more than one place, with the multiple definitions being resolved by the linker as all defining the same thing. HI-TECH C specifically disallows this, since it may lead to subtle bugs. Instead, global variables may be declared extern in as many places as you wish, and must be defined in one and one only place. Typically this will mean declaring global variables in a header file as extern, and defining each variable in the file most closely associated with that variable.

This usage will be portable to virtually all other C implementations.