Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 135 ยท Variables and Types

typedef

Learn C typedef: create type aliases, simplify struct and function pointer declarations, see how size_t and uint32_t work, and know when typedef hides too much.

Some C types are long, some are hard to read, and some change from one machine to another. The typedef keyword lets you give any type a second name. After typedef unsigned long long big_count; you can write big_count wherever you would have written unsigned long long, and the compiler treats the two as exactly the same type.

That sounds like a small convenience, but you rely on typedef every day without noticing: size_t, int32_t, uint8_t, FILE and time_t are all type aliases defined in standard headers. In this lesson you'll learn the syntax, the three places where typedef really pays off (portability, structs and function pointers), and the cases where an alias makes code harder to understand instead of easier.

The syntax: a declaration with typedef in front

The easiest way to read a typedef is this: write a normal variable declaration, then put typedef in front of it. The name that would have been a variable becomes the name of a type instead.

C
unsigned int user_id;            // a variable named user_id
typedef unsigned int user_id;    // a type named user_id

double readings[8];              // an array variable
typedef double reading_row[8];   // a type: "array of 8 doubles"

This rule explains every typedef you'll ever meet, including the scary function pointer ones later in this lesson. The new name goes exactly where the variable name would go.

C Giving types meaningful names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

reading_row is an alias for a whole array type, so sizeof(reading_row) is the size of four doubles (32 bytes on our server), not the size of one.

An alias is not a new type

A typedef creates a new name, never a new type. A celsius and a double are completely interchangeable, and so are two different aliases of the same underlying type. The compiler won't stop you from adding Celsius to Fahrenheit:

C Aliases mix freely with each other

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

So typedef documents intent, but it doesn't enforce it. If you want the compiler to reject mixing two kinds of value, wrap each in its own struct: typedef struct { double value; } celsius; makes celsius a genuinely distinct type that won't silently combine with a plain double.

Portability: the standard library's aliases

The C standard doesn't fix the sizes of int, long and friends (see Data Types). Typedefs fill that gap. A header can define a name once, per platform, and everyone else writes portable code against the name:

Alias Header Meaning
size_t <stddef.h> (and others) unsigned type for sizes and counts; what sizeof returns
ptrdiff_t <stddef.h> signed type for the difference of two pointers
int32_t, uint8_t, โ€ฆ <stdint.h> integers with an exact width
int_least16_t, int_fast32_t <stdint.h> "at least" and "fastest" widths
time_t, clock_t <time.h> time values
FILE <stdio.h> the stream type behind fopen

On a typical 64-bit Linux system uint64_t is a typedef for unsigned long, while on 64-bit Windows it's unsigned long long. Your code says uint64_t and works on both. You met these types in Integer Types.

Names ending in _t are a convention of the standard library, and POSIX reserves them for itself. Many projects still use _t for their own types, and it usually works, but a future system header could clash with your name. A safer habit is a project prefix (app_point) or no suffix at all.

typedef with structures

The most common use of typedef in everyday C is with structures. Without it, a struct type's full name includes the word struct:

C
struct point {
    double x;
    double y;
};

struct point start = {0.0, 0.0};   // "struct" is required every time

There are two usual ways to get a shorter name. You can add a typedef after the struct definition, or you can combine both in one declaration. The struct tag and the alias live in different namespaces, so they may even use the same word:

C
typedef struct point point;        // alias for an existing struct

typedef struct rect {              // tag and alias in one go
    point top_left;
    point bottom_right;
} rect;

typedef struct {                   // anonymous struct: only the alias exists
    unsigned char r, g, b;
} color;

The anonymous form is the shortest, but it has one limit. A struct that points to its own type, like a linked-list node, needs the tag, because the alias doesn't exist yet while the members are being declared:

C typedef for structs, including a self-referential one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You'll build real lists like this in Linked Lists. For now, notice the pattern typedef struct node { ... struct node *next; } node;: it's everywhere in C code.

typedef for function pointers

Function pointers have the most confusing syntax in C. A pointer to a function that takes two ints and returns an int is written int (*op)(int, int), and an array of five of them is int (*ops[5])(int, int). A function that returns such a pointer is worse still. Apply the "put typedef in front" rule once and the rest of the code becomes readable:

C
int (*op)(int, int);                // variable: pointer to function
typedef int (*binary_op)(int, int); // type: pointer to function

binary_op ops[5];                   // array of five such pointers
C A table of operations with a function pointer typedef

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The Function Pointers lesson covers callbacks and qsort comparators in depth. Some programmers prefer to typedef the function type instead (typedef int binary_fn(int, int);) and write the star at each use (binary_fn *op), so that pointers stay visible. Both styles are valid.

typedef versus #define

You could try to create a type name with the preprocessor, #define string char *, but macros are plain text substitution, and that breaks as soon as you declare two variables at once:

C Why a macro is not a type alias

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output shows that b is a single char (size 1), while d is a pointer (size 8): in a declaration, the * belongs to each variable, not to the type in front. A typedef is understood by the compiler, follows scope rules (an alias declared inside a function exists only there), and works with arrays and function pointers, which a macro can't express at all.

C23: typeof and typedef together

C23 adds the typeof operator, which names "the type of this expression". Combined with typedef, it lets you name a type you'd otherwise have to spell out, such as the type of an existing variable or of a function:

C
int scores[10];
typedef typeof(scores[0]) score;   // C23: score is int

typedef typeof(add) arith_fn;      // C23: the function type int(int, int)

GCC and Clang have supported typeof as an extension for decades, so you'll see it in older code too. C11 also made it legal to repeat a typedef as long as it names the same type, which helps when two headers both define the same alias.

When typedef helps and when it hides too much

Good uses of typedef:

  • Portability: a name like sample_t or uint32_t whose underlying type may differ between platforms.
  • Readability of complex declarators: function pointers and pointers to arrays.
  • Structs you use all the time: point, rect, color.
  • Opaque types: a header declares typedef struct parser parser; and functions that take parser *, while the struct's members stay private to one source file. FILE works like this.

Uses that hurt more than they help:

  • Hiding pointers. With typedef struct node *node_ptr;, the reader of node_ptr head can't see that head might be NULL or must be freed, and const node_ptr means "constant pointer", not "pointer to constant data", which surprises almost everyone. Keep the * visible.
  • Renaming basic types for no reason. typedef int integer; adds a word to learn and tells the reader nothing.
  • Hiding structs that callers copy and inspect. The Linux kernel coding style, for example, discourages typedef for ordinary structs so that struct stays visible at every use. Choose one convention for your project and apply it consistently.

A useful test: if the alias tells the reader something the original type didn't (its purpose, its unit, its portability), keep it. If it only saves a few keystrokes while hiding a pointer or a struct, drop it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After typedef double meters; and typedef double seconds;, what happens with meters m = 5.0; seconds s = m;?

    typedef creates aliases, not new types. To make the compiler reject mixing them, wrap each value in its own struct.
  2. 2. Given #define PTR int * and the declaration PTR p, q;, what is the type of q?

    The macro expands to int * p, q;, and the star binds to p only. A typedef such as typedef int *int_ptr; would make both pointers.
  3. 3. Why does a self-referential struct need a tag, as in typedef struct node { struct node *next; } node;?

    The typedef name is introduced only at the end of the declaration, so inside the braces you must refer to the type as struct node.
  4. 4. Which declaration makes handler a type meaning "pointer to a function taking a const char * and returning void"?

    Write the variable declaration void (*handler)(const char *); and put typedef in front. The first option declares a function type returning void *.

Summary

  • typedef gives an existing type a new name: write a declaration and put typedef in front, and the variable name becomes the type name.
  • An alias is the same type as the original; it documents intent but doesn't stop you from mixing values. Wrap values in a struct for real type safety.
  • The standard library uses typedefs for portability: size_t, ptrdiff_t, int32_t, uint64_t, time_t, FILE.
  • typedef struct name { ... } name; is the classic struct idiom; self-referential structs must use the tag inside the braces.
  • Function pointer typedefs (typedef int (*binary_op)(int, int);) make tables of functions and callbacks readable.
  • Prefer typedef over #define for types: macros are text and break with PTR a, b;.
  • Avoid typedefs that hide pointers or rename basic types for no benefit. C23 adds typeof, which works well together with typedef.

Next: Arithmetic Operators