using struct keyword in variable declaration in C++

前端 未结 6 1912
暗喜
暗喜 2020-11-27 07:34

I have a feeling this may be related to C syntax, but I started my programming life with C++ so I am not sure.

Basically I have seen this:

struct tm          


        
6条回答
  •  孤城傲影
    2020-11-27 07:37

    In C, the struct tag names do not form identifiers on the global name space

    struct not_a_global_identifier { /* ... */ };
    

    To refer to that struct you have to use the keyword struct (to specify the name space)

    struct not_a_global_identifer object;
    

    or create a new identifier, in the global name space, with typedef

    typedef struct not_a_global_identifer { /* ... */ } global_name_space_identifier;
    

    There are 4 namespaces in C, see 6.2.3 in the C99 Standard:

    • label names
    • the tags of structures, unions, and enumerations
    • the members of structures or unions (not a single name space ... as many as structures or unions are defined)
    • global name space, for all other identifiers

    This is a legal C program :-)

    int main(void) {
      typedef struct foobar { int foobar; } foobar;
      foobar boo;
      boo.foobar = 42;
      if (boo.foobar) goto foobar;
    foobar:
      return 0;
    }
    

提交回复
热议问题