using struct keyword in variable declaration in C++

前端 未结 6 1928
暗喜
暗喜 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:34

    The user-defined types have their own identifier space, i.e. when the compiler parse the file it stores each identifier in its corresponding space.

    When you refer to tm, the C compiler (as the C++ one) will search for this identifier in the global identifier space. The C++ compiler will then lookup in the user-defined types identifier space if it hadn't found the symbol before.

    Basically, if you want to have the same behavior as in C++, add this line :

    typedef struct tm tm;
    

    You can combine struct declaration and typedef like that :

    typedef struct tm { int field } tm;
    

    Or using a anonymous struct :

    typedef struct { int field } tm;
    

    The same behavior applies for enum and union :

    typedef enum { VALUE } myEnum;
    typedef union { int integer; char charArray[4]; } myUnion;
    

提交回复
热议问题