typedef vs #define in c, you should know

typedef vs #define in C

In my previous post, I have written on typedef and its application. I have found that there is a lot of students and fresher that think typedef and #define both are the same things. In this article, I will describe the differences between the typedef and #define in C (typedef vs #define in C).

typedef :

A typedef defines a new name for existing types and does not introduce a new type. It is the (partial storage-class specifier) compiler directive mainly use with user-defined data types (structure, union or enum) to reduce their complexity and increase the code readability and portability.

You can check this link to know typedef in detail: typedef in C

Syntax:

typedef type NewTypeName;

Let’s take an example,

typedef unsigned int UnsignedInt;
Now UnsignedInt is a new type and using it, we can create a variable of unsigned int.

 

If you want to learn more about the c language, here 10 Free days C video course for you.

C tutorial

#define

A  #define is a pre-processor directive and it replaces the value before compiling the code. One of the major problem with the macro that there is no type checking. Generally, the macro is used to create the alias, in C language macro is also used as a file guard.

For example,

#define Value 10
Now Value becomes 10, in your program, you can use the Value in place of the 10.

There are few points that describe how typedef is different from the #define (typedef vs #define in C)

  • The typedef has the advantage that it obeys the scope rules. That means you can use the same name for the different types in different scope. It can have file scope or block scope in which declare. In other words, #define does not follow the scope rule.

See the below programme for better understanding,

Explanation of the code,
In the above code, both created type have the same name and they declare in the same scope. So when we will compile the code, we will get the compiler error.

Explanation of the code,
When compiling the above code, we will get a warning but will not get a compiler error.

  • typedef is compiler token while #define is a preprocessor token.
  • typedef is ended with semicolon while #define does not terminate with a semicolon.
  • typedef is used to give a new symbolic name to existing type while #define is used to create an alias of any type and value.

See example code,

Explanation of the code,
In above code, when we used CHAR_PTR to declare the variable then Data1 become character pointer and Data2 become character variable. In another case when we used CharPtr to declare the variable then Data3 and Data4 both become character pointer.

 



Leave a Reply