C typedef
In this page:
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?
#include <stdio.h>
typedef unsigned long ulong;
int main() {
ulong x = 100;
printf("%lu", x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
typedef int Age;
int main() {
Age myAge = 25;
printf("%d", myAge);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
typedef int* IntPtr;
int main() {
int x = 5;
IntPtr ptr = &x;
printf("%d", *ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- C typedef
- C Type Casting
- C Bit Fields
- C Variable Length Arrays
- C Command Line Arguments
- C Function Pointers
- C Callback Functions
- C Multidimensional Pointer
- C string.h Functions
- C stdlib.h Functions
- C math.h Functions
- C time.h Functions
- C ctype.h Functions
- C errno.h
- C assert.h
- C Error Handling
- C Debugging Techniques
- C Code Style & Best Practices
- C Common Mistakes
- C Interview Questions