This question already has an answer here:
-
What does “static” mean in C?
18 answers
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;
}
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
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).
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; };
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;
Here the important point is the static local variable. Static local variable will be initialized only one time, and the value will be saved and shared in the hole program context. This means the startw and endw will be used on next timing invoked.
In the program, you can invoke the timing many times:
timing(true);
//startw will be initialzed
timing(false);
//endw is initialized, and the startw has been saved on the prevous invoking.
......
I hope my description is clear. You can see the static local variable is static variable will be saved in global context.