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 p
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.