Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use C typedefs rather than #defines?

Tags:

c

standards

What advantage (if any) is there to using typedef in place of #define in C code?

As an example, is there any advantage to using

typedef unsigned char UBYTE

over

#define UBYTE unsigned char

when both can be used as

void func()
{
        UBYTE byte_value = 0;

        /* Do some stuff */

        return byte_value;
}

Obviously the pre-processor will try to expand a #define wherever it sees one, which wouldn't happen with a typedef, but that doesn't seem to me to be any particular advantage or disadvantage; I can't think of a situation where either use wouldn't result in a build error if there was a problem.

like image 725
me_and Avatar asked Apr 07 '10 10:04

me_and


People also ask

What is the point of Typedefs?

typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to assign alternative names to existing types, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another.

What is the advantage of typedef in C?

The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.

Should I use typedef in C?

typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.

What is the difference between #define and typedef?

typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc. typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.


2 Answers

1) Probably the great advantage is a cleaner code. Usually abusing macros transforms the code in an unmaintainable mess, known as: 'macro soup'.

2) By using a typedef you define a new type. Using a macro you actually substitute text. The compiler is surely more helpful when dealing with typedef errors.

like image 92
Andrei Ciobanu Avatar answered Sep 29 '22 13:09

Andrei Ciobanu


If you do a typedef of an array type, you'll see the difference:

typedef unsigned char UCARY[3];
struct example { UCARY x, y, z; };

Doing that with a #define... no, let's not go there.

[EDIT]: Another advantage is that a debuggers usually know about typedefs but not #defines.

like image 21
Donal Fellows Avatar answered Sep 29 '22 13:09

Donal Fellows