top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of typedef in C?

+3 votes
847 views
What is the use of typedef in C?
posted Dec 21, 2013 by Ashima Dhawan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
The purpose of typedef in C/C++ is to assign alternative names to existing (data) types.

1 Answer

+2 votes

wikipedia:

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.

And:

K&R states that there are two reasons for using a typedef. First, it provides a means to make
a program more portable. Instead of having to change a type everywhere it appears throughout
the program's source files, only a single typedef statement needs to be changed. Second, a
typedef can make a complex declaration easier to understand.

answer Dec 21, 2013 by Anderson
"The purpose of typedef is to assign alternative names to existing types."
" it provides a means to make a program more portable."

This can be done using MACRO too.
So what is better Macro OR typedef.
MACRO is just used for value replacement in program itself before compiling all the macro will get replaced by their values... It's job altogether very different from typedef.


up vote
44
down vote
accepted
No.

#define is a preprocessor token: the compiler itself will never see it.
typedef is a compiler token: the preprocessor does not care about it.

You can use one or the other to achieve the same effect, but it's better to use the proper one for your needs

#define MY_TYPE int
typedef int My_Type;
When things get "hairy", using the proper tool makes it right

#define FX_TYPE void (*)(int)
typedef void (*stdfx)(int);

void fx_typ(stdfx fx); /* ok */
void fx_def(FX_TYPE fx); /* error */
link:- http://stackoverflow.com/questions/1666353/are-typedef-and-define-the-same-in-c
Similar Questions
0 votes
#define MY_STRUCT
typedef struct{ 
...
... 
} my_struct;

Above code is giving me error (MY_STRUCT) is not working as expected, Looks that some silly mistake, please point out as I have wasted many hours?

Sorry for hiding my identity?

+3 votes

typedef int *ptr;
ptr p1, p2;

In this P2 is Integer Pointer or Integer?

+5 votes

In a large project . There is a lots of header files included one another and I do not know the header file in which MYINT is define.

How will I know that MYINT is

#define MYINT int

OR

typedef int MYINT
...