← Back to C Course | Chapter 12: Advanced Topics | Lesson 1 of 20

C typedef

What is typedef?

typedef unsigned long ulong; lets you write ulong instead of the more verbose unsigned long everywhere in your code, which becomes especially valuable for long, unwieldy type names involving pointers or function signatures.

Example: What is typedef?

c
#include <stdio.h>
typedef unsigned long ulong;
int main() {
	ulong x = 100;
	printf("%lu", x);
	return 0;
}

Aliasing Standard Types

For example, typedef int Age; doesn't create a genuinely distinct type the way some languages' type systems would -- Age is fully interchangeable with int, but naming it this way documents the variable's intended meaning at a glance.

Example: Aliasing Standard Types

c
#include <stdio.h>
typedef int Age;
int main() {
	Age myAge = 25;
	printf("%d", myAge);
	return 0;
}

Aliasing Structures

typedef struct {int x; int y;} Point; lets you later declare variables with just Point p; instead of the more verbose struct Point p; -- this shorthand is extremely common in real-world C codebases and libraries.

Example: Aliasing Structures

c
#include <stdio.h>
typedef struct {int x; int y;} Point;
int main() {
	Point p = {3, 4};
	printf("%d %d", p.x, p.y);
	return 0;
}

Aliasing Pointers

typedef int* IntPtr; lets you write IntPtr values[10]; instead of int* values[10];, though this particular use is somewhat controversial since it can obscure that a variable is actually a pointer, making code harder to read for some.

Example: Aliasing Pointers

c
#include <stdio.h>
typedef int* IntPtr;
int main() {
	int x = 5;
	IntPtr ptr = &x;
	printf("%d", *ptr);
	return 0;
}

Best Practices for typedef

Following this convention (like typedef struct {...} Point;) makes it immediately visually clear in code that Point is a typedef'd type rather than a built-in one, helping readers distinguish your custom types from standard ones like int or char at a glance.

Example: Best Practices for typedef

c
#include <stdio.h>
typedef struct {int x; int y;} Point;
int main() {
	Point p = {1, 2};
	printf("%d %d", p.x, p.y);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.