# Why in CPP in some system the RAND_MAX is set to 32K while in others it is 2147483647

## Why in CPP in some system the RAND_MAX is set to 32K while in others it is 2147483647

Contents

Problem Description:

In my CPP system whenever I generate a random number using rand() I always get a value between 0-32k while in some online videos and codes it is generating a value between 0-INT_MAX. I know it is dependent on RAND_MAX. So it there some way to change this value such that generated random number are of the range 0-INT_MAX
Thanks in advance for the help 🙂

``````#include<bits/stdc++.h>
using namespace std;

int main(){
srand(time(NULL));
for(int i=1;i<=10;i++){
cout << rand() << endl;
}
}
``````

I used this code and the random number generated are
5594
27457
5076
5621
31096
14572
1415
25601
3110
22442

While the same code on online compiler gives
928364519
654230200
161024542
1580424748
35757021
1053491036
1968560769
1149314029
524600584
2043083516

## Solution – 1

Yes. Don’t use `rand()`. There are many reasons to not use `rand()`, not the least of which is that it is one of the two worst random number generators ever widely distributed. (The other is RANDU.) Don’t use `rand()`. Ever.

Look for `random()` and `arc4random()` on your system. If you don’t find those, then use the PCG source code here.

## Solution – 2

`rand()` is a very old function, going back to the earliest days of C. In those early days, an `INT_MAX` of 32k was common and well justified. Surely it’s easy to see that `RAND_MAX > INT_MAX` doesn’t make any sense.

As for why some compilers have updated their `RAND_MAX` in the intervening years and some have not, I would guess that it’s down to a commitment to backwards compatibility. I know that I’ve been personally bitten by the 32k limit in Microsoft’s compiler. But Microsoft has long been a champion of backwards compatibility, so I’ll forgive them on this one.

Since C++11 there’s a bunch of new random number functions that have been introduced. They’re better than the old `rand()` in almost every way, except perhaps for ease of use.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.