K
Keith Thompson
This, again, is from the C grammar or compiler view. That's the wrong
way to think about it. The 'typedef' keyword is used by programmers to
define their types and a human being will most of the time define a
thing by giving it a name. Although typedef is not the only way to do
this (struct and enum will also create a name in their special
namespaces), it is ONE possible way and for many the preferred way.
Compilers do not care about natural language semantics of a keyword,
programmers do; 'typealias' would be much less obvious.
I guess Felix won't see this, but ...
I strongly disagree that "That's the wrong way to think about it."
It's a *different* way to think about it.
A typedef creates a new name for an existing type. You can use that
new name as an abstraction, a name for a logical entity distinct
from the original type (as size_t is logically distinct from whatever
its base type is, for example).
But it's just as important to understand that the compiler doesn't
create a new type as it is to understand how to use typedef to
create a logical abstraction.
If nothing else, you need to know that if you accidentally mix your
abstraction with the type it's derived from, the compiler probably
isn't going to help you find the mistake.
For example, this program:
#include <stdio.h>
int main(void)
{
printf("stdin->_fileno = %d\n", stdin->_fileno);
printf("sizeof(int) = %u\n", sizeof(int));
return 0;
}
compiles and runs with no diagnostics on my system, because FILE
and size_t are both typedefs. The program is in some sense wrong
(or at least non-portable) but knowing why the compiler doesn't
catch the errors it requires an understanding of how typedef works
on the language level.
(Of course a compiler *could* recognize the use of typedefs and
print warnings when they're misused.)