Re: Operational and functional differences - #define vs typedef ?
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Thu, 15 Dec 2005 23:09:25 GMT
O Plameras <oscarp@xxxxxxxxxxx> writes:
> Are there differences in terms of functionality
> of,
>
> #define
> and
> typedef ?
>
> By the above I mean any instance when the outcome
> obtained by running two versions (1) and (2) below
> of C codes are different ?
>
> For example,
>
> (1) In one C code, it has:
>
> #define u_ unsigned
> #define uc_ unsigned char
>
> (2) The same C code is re-writtened to:
>
> typedef unsigned u_;
> typdef unsigned char uc_;
#define creates a macro. It's expanded literally at each point where
it's used. Most syntax checking and parsing occurs *after* macros are
expanded.
A typedef creates an alias for a type. Macros and typedefs can be
used similarly, but they're really completely different things.
For example, given:
#define u_ unsigned
you can then declare
_u long x;
because the "_u" expands to "unsigned" before the type name
"unsigned long" is parsed.
In general, typedefs are better than macros for defining type aliases,
because that's what they're designed for, and because the syntax of
type declarations is such that a macro isn't always going to work.
In this particular case, I'd recommend using neither macros nor
typedefs. Someone reading your code is going to know what "unsigned"
and "unsigned char" mean. He won't know what "u_" and "uc_" mean
unless he looks up your typedef.
The names "unsigned" and "unsigned char" are perfectly clear; there's
no benefit in inventing other names for them. (Saving keystrokes
isn't much of a benefit, especially when it makes your code more
difficult to understand.)
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- Follow-Ups:
- References:
- Operational and functional differences - #define vs typedef ?
- From: O Plameras
- Operational and functional differences - #define vs typedef ?
- Prev by Date: Re: Is argv array modifiable ?
- Next by Date: Re: Operational and functional differences - #define vs typedef ?
- Previous by thread: Operational and functional differences - #define vs typedef ?
- Next by thread: Re: Operational and functional differences - #define vs typedef ?
- Index(es):
Relevant Pages
|
Loading