Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

struct

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 "s s;" as a declaration inside a structure, but not correct to have this definition inside a function?

like image 519
Roman Byshko Avatar asked Nov 21 '13 09:11

Roman Byshko


2 Answers

In upper example member s is a local to struct. You cannot use it without using t.s 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.

like image 86
user694733 Avatar answered Sep 30 '22 16:09

user694733


As a struct member, the identifier s is unambiguous, because you'll always address it as somestruct.s or someptr->s.

like image 25
Fred Foo Avatar answered Sep 30 '22 18:09

Fred Foo