typedef

From Wikipedia, the free encyclopedia

typedef is a keyword in the C and C++ programming languages. It is used to give a data type a new name. The intent is to make it easier for programmers to comprehend source code.

Contents

[edit] Usage examples

Consider this code:

int coxes;
int jaffa;
...
coxes++;
...
if (jaffa == 10)
...

Now consider this:

typedef int Apples;
typedef int Oranges;
Apples coxes;
Oranges jaffa;
...
coxes++;
...
if (jaffa == 10)
...

Both sections of code do the same thing. The use of typedef in the second example makes it easier to comprehend what is going on, namely, that one variable contains information about apples while the other contains information about oranges.

One more example:

struct var {
    int data1;
    int data2;
    char data3;
};

Here a user-defined data type var has been defined. To create a variable of the type var, in C, the following code is required:

struct var a;

Let's add the following line to the end of this example:

typedef struct var newtype;

Now, in order to create a variable of type var, the following code will suffice:

newtype a;

The same can be accomplished with the following code:

typedef struct var {
    int data1;
    int data2;
    char data3;
}newtype;

Note that a struct declaration in C++ also defines an implicit typedef — that is, the data type can be referred to as var (rather than struct var) immediately, without any explicit use of the typedef keyword. However, even in C++ it can be worthwhile to define typedefs for more complicated types. For example, a program to manipulate RGB images might find it useful to give the name ImagePointer to the type "pointer to array[3] of int":

typedef int (*ImagePointer)[3];

[edit] Criticisms

Some people are opposed to the extensive use of typedefs. Most arguments center around the idea that typedefs simply hide the actual data type of a variable. For example, Greg Kroah-Hartman, a Linux kernel hacker and documenter, discourages their use for anything except function prototype declarations. He argues that this practice not only unnecessarily obfuscates code, it can also cause programmers to accidentally misuse large structures thinking them to be simple types[1].

[edit] See also

[edit] References

  1. ^ Kroah-Hartman, Greg (2002-07-01). Proper Linux Kernel Coding Style. Linux Journal. Retrieved on 2007-09-23. “Using a typedef only hides the real type of a variable.”

[edit] External links

Languages