将文件范围变量放在结构中?有什么好处

时间:2014-03-26 19:22:23

标签: c

作为C开发人员,我总是习惯将文件范围变量作为自己的变量。

static char myChar;
static char *myCharPtr;

现在我开始让人们看到将这些变量放在结构中,如下所示:

typedef struct
{
    char myChar;
    char *myCharPtr;
} exampleData_s;

static exampleData_s myExampleData;

为什么会这样做?有什么好处?我只看到了缺点:更多的打字,它不会使事情更具可读性。

或者我错过了好处?

1 个答案:

答案 0 :(得分:3)

它减少了名称空间污染,特别是对于简单的变量名称,如xylength等。如果将这些变量放在结构中,则没有歧义关于你在代码中引用哪个变量。


例如,我已经使用这种技术在各种程序中收集统计数据。

typedef struct
{
    int count;
    int failed;
    int insize;
    int outsize;
    int bloated;
}
    stStats;

static stStats stats;

int main( void )
{
    memset( stats, 0, sizeof(stats) );

    // the following code is pseudo code for illustrative purposes only (it doesn't compile)
    while ( !done )
    {
        stats.count++;

        if ( something bad happens )
            stats.failed++;
    }
}