Monday, May 26, 2008

Using typedef to Curb Miscreant Code [by Danny Kalev, C++ Pro]

Defining Mnemonic Type Names

The most common use of typedef is creating mnemonic type names that document the programmer's intention. The type being declared appears in the position of a variable's name, right after the keyword 'typedef'. For example,

typedef int size;

This declaration defines a synonym for int called size. Notice that a typedef doesn't create a new type; it merely adds a synonym for some existing type. You can use size in any context that requires int:

void measure(size * psz);
size array[4];
size len = file.getlength();

typedef may also disguise composite types such as pointers and arrays. Define a typedef that will be used every time you need an array of the same type and size:

typedef char Line[81];
Line text, secondline;
getline(text);

Similarly, hide pointer syntax like this:

typedef char * pstr;
int mystrcmp(pstr, pstr);

This brings us to the first typedef trap.
The standard function strcmp() takes two arguments of type 'const char *'. Therefore, it might be tempting to declare mystrcmp() like this:
int mystrcmp(const pstr, const pstr);
This is wrong, though. The sequence 'const pstr' is interpreted as 'char * const' (a const pointer to char), rather than 'const char *' (a pointer to const char).

You can easily solve this problem, though:
typedef const char * cpstr; //a pointer to const char
int mystrcmp(cpstr, cpstr); //now correct

Remember: Whenever you declare a typedef for a pointer, adding const to the resulting typedef name makes the pointer itself const, not the object.

No comments: