Can #define replace typedef

W

WANG Cong

Is there any particular point that makes typedef different than
#define

For example,

if you use #define to define a new type, like this:

#define foo_t unsigned int *

then,

foo_t a, b;

'a' has type of 'unsigned int *', while 'b' has type of
'unsigned int'.

If you use typedef, you will get the correct behavior.

typedef unsigned int * foo_t;
foo_t a, b;

Both 'a' and 'b' have a pointer type.
 
P

parag_paul

For example,

if you use #define to define a new type, like this:

#define foo_t unsigned int *

then,

foo_t a, b;

'a' has type of 'unsigned int *', while 'b' has type of
'unsigned int'.

If you use typedef, you will get the correct behavior.

typedef unsigned int * foo_t;
foo_t a, b;

Both 'a' and 'b' have a pointer type.

thanks Wang
 
S

sg

#include <iostream>
using namespace std;

typedef unsigned int * foo_t;
//#define foo_t unsigned int*

int main(void)
{
foo_t a, b;
//unsigned int* a, b; // Will not work

unsigned int c = 10;

a = &c;
b = &c;

cout << *a << endl << *b << endl;

return 0;
}

Regards
Sandeep
thanks Wang

I think parag has already solve your doubt. I am giving an example in C
++ for the better understanding
 
R

red floyd

Is there any particular point that makes typedef different than
#define

Yes. #defines do not respect scope. No matter what context you are
in, the #define takes effect. It's pure textual substitution that
occurs before almost every other phase of compilation.

A typedef, on the other hand, is part of the language syntax (as opposed
to the preprocessor). It respects scope.
 
J

Juha Nieminen

WANG said:
For example,

if you use #define to define a new type, like this:

#define foo_t unsigned int *

then,

foo_t a, b;

'a' has type of 'unsigned int *', while 'b' has type of
'unsigned int'.

There are also some types which are basically impossible to implement
as a #define. For instance:

typedef int(*FunctionPointer)(int);

// Usage example:
int foo(FunctionPointer fptr)
{
return fptr(5);
}

Another example:

typedef int color[3];

// Usage example:
color c;
c[0] = 10;
 
W

WANG Cong

Juha said:
There are also some types which are basically impossible to implement
as a #define. For instance:

True, typedef "encapsulates" a new type in syntax, which happens during
compile time, #define does things literally, which happens during pre-
process time, before compiling.
 

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

Similar Threads


Members online

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top