问题
Since I found this particular documentation on https://www.tutorialspoint.com/c_standard_library/c_function_rand.htm,I have been thinking about this particular line of code srand((unsigned)time(&t));
.Whenever I had to generate some stuff,I used srand(time(NULL))
in order not to generate the same stuff everytime I run the program,but when I came across this,I have been wondering :Is there any difference between srand((unsigned)time(&t))
and srand(time(NULL))
?Because to me they seem like they do the same thing.Why is a time_t variable used?And why is the adress operator used in srand()
?
#include <stdio.h>
#include<stdlib.h>
int main(){
int i,n;
time_t t;
n = 5;
srand((unsigned)time(&t));
for (i = 0; i < n; i++) {
printf("%d\n", rand() % 50);
}
return(0);
}
回答1:
Yes, it will yield the same result. But the example is badly written.
I would be careful reading Tutorialspoint. It's a site known for bad C code, and many bad habits you see in questions here at SO can be traced to that site. Ok, it's anecdotal evidence, but I did ask a user here why they cast the result of malloc
, and they responded that they had learned that on Tutorialspoint. You can actually see (at least) four examples in this short snippet.
- They cast the result from the call to
time()
which is completely unnecessary and just clutters the code. - For some reason they use the variable
t
, which is completely useless in this example. If you read the documentation fortime()
you'll see that just passing NULL is perfectly adequate in this example. - Why use the variable
n
? For this short example it's perfectly ok with a hardcoded value. And when you use variables to avoid hardcoded values, you should declare themconst
and give them a much more descriptive name thann
. - Omitted
#include<time.h>
which would be ok if they also omitted the rest of the includes.
One could also argue about two other things, but some people would disagree about these.
- Why declare
i
outside the for loop? Declaring it inside have been legal since C99, which is 20 years old. - Why end the function with
return 0
? Omitting this is also ok since C99. You only need to have a return in main if you want to return something else than 0.
Both above are good to remember if your goal is to maintain very old C code in environments where you don't have compilers that supports C99. But how common is that?
So if I got to rewrite the example at tutorialspoint, i'd write it like this:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
srand(time(NULL));
for (int i = 0; i < 5; i++) {
printf("%d\n", rand() % 50);
}
}
One thing they made good is that they used int main()
instead of int main(int argc, char **argv)
. There's no reason to use the second signature if you're not using the variables.
来源:https://stackoverflow.com/questions/55731494/how-does-this-implementation-of-randomization-work-in-c