C Typedef

The C programming language provides the support of declaring alias names to the data types (user defined and primitive) using the keyword typedef.

Syntax

typedef data_type ALIAS;

By convention, uppercase letters should be used for an Alias name, however, this is not a hard and fast rule.

Code Example

#include<stdio.h>

// typedef with struct Method 1
typedef struct Cars {
    char name[20];
    float speed;
}Car;

// typedef with struct Method 2
struct Point {
  int x;
  int y;
};

// struct Point is now only POINT
typedef struct Point POINT;

int main(void)
{
    // Alias Used
    Car c;
    POINT p;

    // typdef for primitive datatypes
    typedef long long int LNG;

    // Alias Used
    LNG var = 123456789;
   
    return 0;
}

typedef vs #define

While both of them is used to declare Alias names, however, typedef is only limited to datatypes. Using #define one can give an alias name to a constant like 3.14 as PI. Also, typdef is interpreted by compiler whereas #define is interpreted by the preprocessor.

Trending

C Programming

Remember to follow community guidelines and don't go off topic.