Reputation: 11
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int n, m;
printf("Enter the lower bound (n): ");
scanf("%d", &n);
printf("Enter the upper bound (m): ");
scanf("%d", &m);
if (n > m)
{
printf("Invalid range. Ensure that n <= m.\n");
return 1;
}
srand(time(0)); //(here)
int randomInRange = (rand() % (m - n + 1)) + n;
printf("Random number between %d and %d: %d\n", n, m, randomInRange);
return 0;
}
when i tried changing the value in srand(time(0)) to srand(time(1)) the code runs, takes the user input of n and m but in the end it doesn't give any output. Why is this happening?
Upvotes: -4
Views: 83
Reputation: 21
The time
function, actually expects a pointer as an argument. Passing 0 is the same thing as passing NULL. That's why you see people use either srand(time(0)
or srand(time(NULL)
. Passing 1 as an argument causes the program inproperly, because 1 is not a valid memory address (pointer).
Upvotes: 1
Reputation: 134316
To make is superfluous, the call
srand(time(0));
can also be written as
srand(time((void *)0));
which is equivalent to
srand(time(NULL));
In other words, the 0
here holds a special meaning, it is not considered as an integer argument, it is passed to the function as a null pointer constant. Changing that to integer value 1
breaks the function call (as opposed to the function signature, see the man page).
Further reading: Chapter 6.3.2.3, Pointers:
An integer constant expression with the value
0
, or such an expression cast to typevoid *
, is called a null pointer constant. ...
Upvotes: 1