Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Using typedef to Curb Miscreant Code-2 : Page 2

Defining Mnemonic Type Names
The most common use of typedefs 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(); std::vector <size> vs;

typedefs may also disguise composite types such as pointers and arrays. For example, instead of repeatedly declaring an array of 81 characters like this:

char line[81]; char text[81];

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; 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.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date