4

Are typedef's handled by C's preprocessor?

That is, is typedef int foo_t; the same as #define foo_t int?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 2
    In a word: no. (oops, that's too short for SO comments) – Barmar Sep 18 '15 at 16:32
  • 1
    `typedef` is treated as a storage-class specifier (along with `extern`, `static`, `auto`, `register`) for syntax purposes, although it isn't really a *storage class*. It just indicates that instead of declaring an *object* of type `T`, it declares a *synonym* for type `T`. – John Bode Sep 18 '15 at 16:54

4 Answers4

3

No, because that type of replacement won't work with more complex types. For instance:

typedef int tenInts[10];
tenInts myIntArray;

The declaration of myIntArray is equivalent to:

int myIntArray[10];

To do this as a macro you'd have to make it a function-style, so it can insert the variable name in the middle of the expansion.

#define tenInts(var) int var[10]

and use it like:

tenInts(myIntArray);

This also wouldn't work for declaring multiple variables. You'd have to write

tenInts(myArray1);
tenints(myArray2);

You can't write

tenInts myArray1, myArray2;

like you can with a typedef.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

No.


As an example,

typedef int *int_ptr1;
#define int_ptr2  int *

Then in:

int_ptr1 a, b;
int_ptr2 c, d;

a and b are both pointers to int. c is also a pointer to int, but d is an int.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

No ,typedef( being a C keyword) is interpreted by compiler not by pre-processor whereas #define is processed by pre-processor.

ameyCU
  • 16,489
  • 2
  • 26
  • 41
-1

No - the C preprocessor doesn't handle typedefs. The C preprocessor does not recognize the syntax of the C language; it will not know what is and is not a typedef.

The #define is strictly a text replacement of "int" for "foo_t"; the replacements done by the preprocessor occur prior to compilation.

A B
  • 4,068
  • 1
  • 20
  • 23