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?
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:
I hope my description is clear. You can see the static local variable is static variable will be saved in global context.
struct timeval
is a struct declared somewhere insys/time.h
. That line you highlighted declares two static variables namedstartw
andendw
of typestruct timeval
. Thestatic
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:Then you've declared (and defined here) a type called
struct foo
. You'll need to usestruct foo
whenever you want to declare a variable (or parameter) of that type. Or use a typedef to give it another name.