我是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;
}
Run Code Online (Sandbox Code Playgroud)
我之前从未遇到过以这种方式定义的静态结构.通常,struct前面是struct的定义/声明.但是,这似乎表明将存在类型为timeval,startw,endw的静态struct变量.
我试图阅读它的作用,但还没有找到足够好的解释.有帮助吗?
struct timeval
是在某处声明的结构sys/time.h
.您突出显示的那一行声明了两个名为startw
和endw
类型的静态变量struct timeval
.该static
关键字适用于声明的变量,而不适用于struct(type).
你可能更习惯于有一个typedef
名字的结构,但这不是必需的.如果你声明一个像这样的结构:
struct foo { int bar; };
Run Code Online (Sandbox Code Playgroud)
然后你已声明(并在此定义)一个名为的类型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;
Run Code Online (Sandbox Code Playgroud)