I am trying to understand the difference between a typedef and define. There are a lot of good posts specially at this previous question on SO, however I can't understand the post that states
#define
is a preprocessor token: the compiler itself will never see it.typedef
is a compiler token: the preprocessor does not care about it.
Could anyone please explain this with a little more detail. I am confused with the term preprocessor here.
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.
The preprocessor is a part of the compiler which performs preliminary operations (conditionally compiling code, including files etc...) to your code before the compiler sees it. These transformations are lexical, meaning that the output of the preprocessor is still text.
Advertisements. The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation.
This preprocessor directive is used to provide additional information to the C compiler. It offers machine or operating-system features to the compiler. Different compilers have different usage of the #pragma directive.
The pre-processor is a program that runs before the compiler and essentially performs text substitution. When you write:
#define X 10
int main()
{
int x = X;
}
The pre-processor take that file as input, does it's thing, and outputs:
int main()
{
int x = 10;
}
And then the compiler does its thing with the pre-processed output.
typedef
on the other hand is a construct that the compiler understands. When you write:
typedef unsigned int uint_32;
The compiler knows that uint32
is actually an alias for unsigned int
. This alias is handled by the compiler itself and involves a bit more logic than simple text substitution. This becomes obvious with a simple example:
typedef int my_int;
int main()
{
unsigned my_int x; // oops, error
}
If a typedef
were a simple text substitution mechanism (like the pre-processor is) then that would work, but it is not allowed and will fail to compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With