我对 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;
}
我以前从未遇到过以这种方式定义的静态结构。通常结构前面是结构的定义/声明。然而,这似乎表明将会有 timeval、startw、endw 类型的静态结构变量。
我试图了解它的作用,但尚未找到足够好的解释。有什么帮助吗?
struct timeval
是一个在某处声明的结构体sys/time.h
。您突出显示的那一行声明了两个名为startw
and endw
类型的struct timeval
. The static
关键字适用于声明的变量,而不是结构(类型)。
您可能更习惯于具有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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)