Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random int in C?

Tags:

c

random

Is there a function to generate a random int number in C? Or will I have to use a third party library?

like image 265
Kredns Avatar asked May 04 '09 22:05

Kredns


People also ask

Is there a random function in C?

C library function - rand() The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.


1 Answers

Note: Don't use rand() for security. If you need a cryptographically secure number, see this answer instead.

#include <time.h> #include <stdlib.h>  srand(time(NULL));   // Initialization, should only be called once. int r = rand();      // Returns a pseudo-random integer between 0 and RAND_MAX. 

On Linux, you might prefer to use random and srandom.

like image 64
Łukasz Lew Avatar answered Sep 24 '22 00:09

Łukasz Lew