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 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 char Line[81];
Line text, secondline;
getline(text);
Similarly, hide pointer syntax like this:
typedef char * pstr;
int mystrcmp(pstr, pstr);
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).
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.
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:
Post a Comment