关于C与C++的struct,union,enum用法差异

对着代码说话:

#include <stdio.h>
#include <stdlib.h>

struct test
{
    int abc;
};

enum _enum {A,B,C};

union _union
{
    int abc;
    double cdf;
};

int main()
{
    struct test t;
    enum _enum a;
    union _union u;
    printf("Hello world!\n");
    return 0;
}

  • 在C中声明struct, enum, union时需要在类型前面加上这些关键字修改,否则报错。而C++则不用。
  • 在C中使用typedef定义类型,可以省略struct,union,enum关键字。而这也是nginx的习惯用法,例如:
#include <stdio.h>
#include <stdlib.h>

struct test_s
{
    int abc;
};

typedef struct test_s test;

enum _enum_e {A,B,C};

typedef enum _enum_e _enum;

union _union_u
{
    int abc;
    double cdf;
};

typedef union _union_u _union;

int main()
{
    test t;
    _enum a;
    _union u;
    printf("Hello world!\n");
    return 0;
}

posted @ 2016-09-05 16:53  zolo®  阅读(268)  评论(0编辑  收藏  举报