Zexon
Zexon

Reputation: 15

How to understand this usage of typedef?

Here's the code:

typedef char FlagType;

int main()
{
}

int myproc( int )
{
    int FlagType;
}

copied from https://learn.microsoft.com/en-us/cpp/c-language/typedef-declarations?view=msvc-160

In my understanding, 'typedef char FlagType' makes 'char a' and 'FlagType a' no difference. But I can't understand the 'int FlagType'.

Upvotes: 1

Views: 63

Answers (2)

Lior Kogan
Lior Kogan

Reputation: 20608

The code demonstrates a pathological example. Not a standard or recommended use case.

It is shown to explain what happens when a local variable has the same name as a typedef name.

Typedef names share the name space with ordinary identifiers (see Name Spaces for more information). Therefore, a program can have a typedef name and a local-scope identifier by the same name.

Upvotes: 4

PaulProgrammer
PaulProgrammer

Reputation: 17630

If you read a few lines above, they're describing how the namespaces are separated.

This example shows a typedef of type char named FlagType and a variable in myproc() of type int named FlagType.

This is stupid, and nobody should do it, but it is legal from a language parsing standpoint.

I had the same "WTF‽" reaction when I first learned of nested anonymous structures.

Upvotes: 1

Related Questions