0
0
CHow-ToBeginner · 3 min read

How to Create Alias Using typedef in C: Simple Guide

In C, you create an alias for an existing type using the typedef keyword followed by the original type and the new name. For example, typedef int Number; makes Number an alias for int, so you can use Number instead of int in your code.
📐

Syntax

The basic syntax of typedef is:

  • typedef: keyword to create an alias.
  • existing_type: the original data type you want to rename.
  • new_name: the new alias name you want to use.

The alias can then be used as a type in your program.

c
typedef existing_type new_name;
💻

Example

This example shows how to create an alias Number for int and use it to declare variables.

c
#include <stdio.h>

typedef int Number;

typedef struct {
    Number x;
    Number y;
} Point;

int main() {
    Number a = 10;
    Point p = {5, 7};
    printf("a = %d\n", a);
    printf("Point p: x = %d, y = %d\n", p.x, p.y);
    return 0;
}
Output
a = 10 Point p: x = 5, y = 7
⚠️

Common Pitfalls

Common mistakes when using typedef include:

  • Confusing the order: typedef comes first, then the existing type, then the new name.
  • Trying to use typedef like a variable declaration (it only creates aliases).
  • Not remembering that typedef does not create new types, just new names.
c
/* Wrong way: */
// int typedef Number;  // Syntax error

/* Right way: */
typedef int Number;
📊

Quick Reference

UsageDescription
typedef int Number;Creates alias 'Number' for 'int'
typedef struct { int x; int y; } Point;Creates alias 'Point' for a struct type
Number a;Declares variable 'a' of type 'int' using alias
Point p;Declares variable 'p' of struct type using alias

Key Takeaways

Use typedef to create a new name for an existing type in C.
The syntax is typedef existing_type new_name; with the new name last.
Aliases help make code clearer and easier to change later.
typedef does not create new types, only new names.
Remember to place typedef before the original type and alias.