C:静态结构

时间:2014-03-08 15:04:18

标签: c struct

我是C的新手,我正在查看一些代码以了解哈希。

我遇到了一个包含以下代码行的文件:

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

#include <time.h>
#include <sys/time.h>

// ---------------------------------------------------------------------------

int64_t timing(bool start)
{
    static      struct timeval startw, endw; // What is this?
    int64_t     usecs   = 0;

    if(start) {
        gettimeofday(&startw, NULL);
    }
    else {
        gettimeofday(&endw, NULL);
        usecs   =
               (endw.tv_sec - startw.tv_sec)*1000000 +
               (endw.tv_usec - startw.tv_usec);
    }
    return usecs;
}

我以前从未遇到过以这种方式定义的静态结构。通常,struct前面是struct的定义/声明。但是,这似乎表明将存在类型为timeval,startw,endw的静态struct变量。

我试图了解它的作用,但还没有找到足够好的解释。有什么帮助吗?

2 个答案:

答案 0 :(得分:6)

struct timeval是在sys/time.h中声明的结构。您突出显示的那一行声明了两个名为startwendw类型为struct timeval的静态变量。 static关键字适用于声明的变量,而不适用于struct(type)。

您可能更习惯于使用typedef'名称的结构,但这不是必需的。如果你声明一个这样的结构:

struct foo { int bar; };

然后你声明了(并在这里定义)一个名为struct foo的类型。只要您想声明该类型的变量(或参数),就需要使用struct foo。或者使用typedef为其命名。

foo some_var;              // Error: there is no type named "foo"
struct foo some_other_var; // Ok
typedef struct foo myfoo;
myfoo something_else;      // Ok, typedef'd name
// Or...
typedef struct foo foo;
foo now_this_is_ok_but_confusing;

答案 1 :(得分:1)

这里重要的是静态局部变量。 静态局部变量将初始化一次,值将保存并在孔程序上下文中共享。这意味着 startw endw 将在下一次计时上被使用。

在程序中,您可以多次调用计时

timing(true);
//startw will be initialzed
timing(false);
//endw is initialized, and the startw has been saved on the prevous invoking.
......

我希望我的描述清楚。您可以看到静态局部变量 静态变量将保存在全局上下文中。