typedef vs #define

R

riccardo

Hi NG,
could you please tell me which is the best option among the following two?

/* 1) */ typedef int foodata1;

/* 2) */ #define foodata2 int

Thanks in advance.
 
B

Ben Bacarisse

riccardo said:
could you please tell me which is the best option among the following two?

/* 1) */ typedef int foodata1;

/* 2) */ #define foodata2 int

Most people will go for 1. It is the proper way to write a type
definition. There will be circumstances where 2 is useful (for example
if you need to string-ify the type or you need to construct macros that
incorporate the type name) but you don't give any context and these are
unusual situations.
 
J

John Bode

Hi NG,
could you please tell me which is the best option among the following two?

   /* 1) */ typedef int foodata1;

   /* 2) */  #define foodata2 int

Thanks in advance.

If you need to create a synonym for a type name, use typedef (option
1); that's what it's there for. For simple types like "int" or
"double" it's hard to see a difference, but when you have something
truly ugly like

double *(*(*f)())[10];

the typedef solution is the safer and easier way to go:

typedef double *(*ptrArrPtrDbl)[10]; // ptrArrPtrDbl== double
*(*)[10]
typedef ptrArrPtrDbl (*uglyFuncPtr)(); // uglyFuncPtr == double
*(*(*)())[10]
...
uglyFuncPtr myUglyFuncPtr;
...
dblPtrArrPtr myArr = myUglyFuncPtr(); // or (*myUglyFuncPtr)();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,954
Messages
2,570,114
Members
46,702
Latest member
VernitaGow

Latest Threads

Top