Are `typedef` and `struct` inside of a function standard in C?

eonil picture eonil · Apr 8, 2011 · Viewed 19.2k times · Source

I used some code like this:

void A()
{
    typedef struct B B;
    struct B
    {

    };

    B b;
};

typedef and struct definition inside a function. It compiled with Clang, but I want to know (1) whether they are part of standard or not. And about (2) whether they are limited to be recognized in function scope only.

Answer

Jerry Coffin picture Jerry Coffin · Apr 8, 2011

Yes, the standard allows this, and yes, the name you create this way is only visible inside the function (i.e., it has local scope, just like when you define int i;, i has local scope).

It's more common, however to do it something like this:

typedef struct { 
    /* ... */ 
} B;
B b;