C:静态结构
我是C的新手,我正在查看一些代码来了解哈希。
我遇到了一个包含以下代码行的文件:
#include #include #include #include #include #include // --------------------------------------------------------------------------- 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变量。
我试着读一下它的作用,但还没有找到足够好的解释。 有帮助吗?
struct timeval
是在sys/time.h
声明的结构。 您突出显示的那一行声明了两个名为startw
和endw
的类型为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;
这里重要的是静态局部变量。 静态局部变量将仅初始化一次,并且将在孔程序上下文中保存和共享该值。 这意味着startw和endw将在下一次调用时使用。
在程序中,您可以多次调用时间:
timing(true); //startw will be initialzed timing(false); //endw is initialized, and the startw has been saved on the prevous invoking. ......
我希望我的描述清楚。 您可以看到静态局部变量是静态变量将保存在全局上下文中。