简体   繁体   中英

What is the difference between structure and function scope in C?

Consider this piece of code

   int main(void)
   {
       typedef struct {
           int i;
       } s;

       struct {
           s s;
       } t;

       return 0;
   }

It compiles fine. Now take a look at this one

   int main(void)
   {
       typedef struct {
           int i;
       } s;

       s s;
       return 0;
   }

This code will not compile -

‘s’ redeclared as different kind of symbol.

Question: Why is it correct to have "ss;" as a declaration inside a structure, but not correct to have this definition inside a function?

In upper example member s is a local to struct. You cannot use it without using ts syntax, so there is no conflict with structure type s .

In lower example structure type s , and variable s are in the same scope, so it is unclear which you are referring to.

作为struct成员,标识符s是明确的,因为您将始终将其作为somestruct.ssomeptr->s

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