问题描述
我对 C 比较陌生,正在复习一些代码以了解散列.
I am fairly new to C and am going over some code to learn about hashing.
我发现了一个包含以下代码行的文件:
I came across a file that contained the following lines of code:
#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;
}
我以前从未遇到过以这种方式定义的静态结构.通常结构前面是结构的定义/声明.然而,这似乎只是表明将有类型为 timeval、startw、endw 的静态结构变量.
I have never come across a static struct defined in this manner before. Usually a struct is preceded by the definition/declaration of the struct. However, this just seems to state there are going to be static struct variables of type timeval, startw, endw.
我试图阅读它的作用,但还没有找到足够好的解释.有什么帮助吗?
I have tried to read up on what this does but have not yet found a good enough explanation. Any help?
推荐答案
struct timeval
是一个在 sys/time.h
中声明的结构体.您突出显示的那一行声明了两个名为 startw
和 endw
且类型为 struct timeval
的静态变量.static
关键字适用于声明的变量,而不是结构体(类型).
struct timeval
is a struct declared somewhere in sys/time.h
. That line you highlighted declares two static variables named startw
and endw
of type struct timeval
. The static
keyword applies to the variables declared, not the struct (type).
您可能更习惯于具有 typedef
名称的结构,但这不是必需的.如果你像这样声明一个结构体:
You're probably more used to structs having a typedef
'd name, but that's not necessary. If you declare a struct like this:
struct foo { int bar; };
然后您已经声明(并在此处定义)一个名为 struct foo
的类型.每当您想声明该类型的变量(或参数)时,您都需要使用 struct foo
.或者使用 typedef 给它另一个名字.
Then you've declared (and defined here) a type called struct foo
. You'll need to use struct foo
whenever you want to declare a variable (or parameter) of that type. Or use a typedef to give it another name.
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;
这篇关于C:静态结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!