Re: difference between typedef and #define



On Thu, 30 Jun 2005 18:06:41 -0500, Drew Myers wrote:

> But if I, without using typedef or #define write:
>
> int* i,j,k; // * next to int and not next to i
>
> all of the variables are int*

No, only i is int*. The rest are int.

For background on this, see:

Is ``int* p;'' right or is ``int *p;'' right?
http://www.research.att.com/~bs/bs_faq2.html#whitespace

> whereas:
>
> int *i,j,k; // * next to i and not next to int
>
> produces the results you explain. Why does typedef/#define
> behave differently than typing it out as I did above?

Macros do pure textual substitution. So, given:

#define T int*
T i, j, k;

The preprocessor turns this into:

int* i, j, k;

The typedef mechanism is different. It doesn't do textual substitution but
instead creates synonyms for types. So, given:

typedef int* T;
T i, j, k;

This results in all the variables having the type T, which is int*. To see
another difference, consider:

const T x;
T const x;

The const (or volatile) applies to the variable x in the first case as well
as the second, not to the referent (i.e. *x), and that's another difference
between the macro T and typedef T. So, when you write a pointer or
reference typedef, you should also provide const/volatile forms as
necessary, and your users will have to learn to use LPCSTR instead of
"const LPSTR" or "LPSTR const", to use a Windows example.

--
Doug Harrison
Microsoft MVP - Visual C++
.



Relevant Pages

  • [UNIX] ELFdump Crash when Analyzing Crafted ELF File
    ... The following security advisory is sent to the securiteam mailing list, and can be found at the SecuriTeam web site: http://www.securiteam.com ... typedef unsigned char uint8_t; ... int GetArgs ... const char * const, ...
    (Securiteam)
  • Bypassing Personal Firewalls
    ... typedef SOCKET (int, int, int); ... typedef int (__stdcall *func_connect)(SOCKET, const struct sockaddr ... typedef HANDLE (LPCTSTR, DWORD, DWORD, ...
    (Bugtraq)
  • Bypassing Personal Firewalls
    ... typedef SOCKET (int, int, int); ... typedef int (__stdcall *func_connect)(SOCKET, const struct sockaddr ... typedef HANDLE (LPCTSTR, DWORD, DWORD, ...
    (Vuln-Dev)
  • Re: formal parameter 1 different from declaration?
    ... Here is the typedef one: ... typedef LR (HWND, long, int, int); ... struct tagWnd; // forward declaration ... takes a struct tagHwnd and the other takes a long. ...
    (microsoft.public.vc.language)
  • Re: I dont understand typedef example
    ... * Using typedef, declare 'func' to have type ... 'function taking two int arguments, ... declared ptr as a pointer object that can points to a function of the ...
    (comp.lang.c)