Published: Sunday, December 17, 2023, Updated: Sunday, December 17, 2023

Difference Between Typedef and Define in C with Example

In C, both #define and typedef are used for defining new names, but they serve different purposes and have some key differences.

#define:

Purpose:

  • #define is a preprocessor directive used to create symbolic constants or macros.
  • It doesn't create a new type; rather, it performs text substitution before the actual compilation process.

Example:

   #include <stdio.h>

   // Define a constant using #define
   #define PI 3.14159

   int main() {
       // Use the defined constant
       double radius = 5.0;
       double area = PI * radius * radius;

       printf("Area of the circle: %f\n", area);

       return 0;
   }

In this example, #define PI 3.14159 defines a macro PI that will be replaced with its value during preprocessing.

typedef:

Purpose:

  • typedef is used to create new names for existing data types.
  • It enhances code readability and can be especially useful when you want to create more descriptive names or abstract away implementation details.

Example:

   #include <stdio.h>

   // Define a typedef for int
   typedef int Age;

   int main() {
       // Use the typedef
       Age myAge = 25;

       // Print the age
       printf("My age is %d years.\n", myAge);

       return 0;
   }

In this example, typedef int Age; creates a new name (Age) for the existing data type int.

Differences:

  • #define is a preprocessor directive that performs text substitution, whereas typedef creates an alias for an existing type, providing a new name for it.
  • #define is not limited to type definitions; it is commonly used for defining constants and macros.
  • typedef is specifically used for creating aliases for data types, improving code readability and maintainability.
  • #define is processed by the preprocessor, and the substitution occurs before compilation, whereas typedef is part of the actual C code and is processed by the compiler.

In summary, #define is more versatile, used for defining constants and macros, while typedef is used for creating aliases for existing data types, making code more readable and maintainable.

Elliyas Ahmed
Elliyas Ahmed
Elliyas Ahmed, founder of COMPROMATH, is a Computer Science and Engineering graduate who excels in Blogging, Website Development, and SEO. He offers freelancing services to help clients succeed online. Learn more about Elliyas Ahmed.