简体   繁体   中英

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

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.

Yes, the standard allows this, and yes, the name you create this way is only visible inside the function (ie, 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;

Yes it is allowed. but you cannot have
function inside a function.

declarations should be done first and later on you can do with your actual code.

you cannot declare after you do some operation inside your function like below

void A()
{

int a=0;

a++;    

typedef struct B B;//this is wrong
    struct B
    {

    };

    B b;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM