I'm posting this in the beginners section because there's probably a stupidly obvious reason as to why it wouldn't work.
My question to you guys today is this: Why use random functions when you can use the address or initial value of a number? For instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <cstdio>
#include <cstdlib>
#include <ctime>
int main(){
int rand_num;
srand(time(0));
//random number between 0 and 100
printf("Function: %i\nAddress: %i\n\
Initial: %i\n\nPress <ENTER> to continue",
rand()%100,int(&rand_num)%100,rand_num%100);
getchar();
return 0;}
Sorry if i made any typos or the code looks squashed... I'm on my iPhone.
Good question... i think its because if we use variables for getting random numbers wed have variables all over the place
But i cant think of any other reason.
Are the numbers always different? If so you coud just make a random function like; int rand(){int i; return i;}
edit;
Also i believe random functions are made so that they arent often the same value
Like if you would use rand()%2 a million times, you wouldnt get 0 a million times, most likely half a million for both 0 and 1, but not exactly half a million ofcourse
Because the value of an uninitialized variable isn't random, it's undefined.
Big difference. Neither addresses nor these values are very random in practice (well, addresses one address in main (all other stack variables are relative to that) can be somewhat random when your OS uses ASLR).
The value of an uninitialized variable is those of the object that occupied that address before. Not very random. Particularly one value (0) is by far the most probable here. A stack variable in a function will also always* have the same address when the callstack is the same.
What about seeding a random function with an address?
1 2 3 4 5 6 7 8 9 10 11 12
#include <cstdio>
#include <cstdlib>
int main(){
int rand_num;
srand(int(&rand_num));
//random number between 0 and 100
printf("1st: %i\n2nd: %i\n3rd: %i",
rand()%100,rand()%100,rand()%100);
getchar();
return 0;}
That's also bad, because there's a limited number of possible addresses rand_num can have (with ASLR) - without ASLR it's just one possible address. Windows XP and earlier don't have ASLR and they're widely used operating systems.
time(0) is much more suitable as a seed value, since the value changes every second and will never be used again in the next 136 years.
Just to add to what was said above. I believe most implementations of rand rollow a uniform random distribution. I'm almost certain that taking an address does not follow a uniform random distribution