Will rand() sometimes return the same consecutively?

If we can find one example where it does, the answer to your question is “yes”.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
  unsigned int i;
  for(i = 0; ; i++) {
    int r = rand();
    if (r == rand()) {
        printf("Oops. rand() = %d; i = %d\n", r, i);
        break;
    }
  }
  return 0;
}

prints Oops. rand() = 3482; i = 32187 on Windows with Visual Studio 2010.

EDIT:
Use the version below to detect all sequences where 2 consecutive rand() calls return the same value.
C only specifies that rand() should return “pseudo-random integers in the range 0 to
RAND_MAX” and RAND_MAX should be at least 32767.
There are no constraints on the quality of the PRNG, or it’s implementation, or other details such as whether 2 consecutive rand() calls can return the same value.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
  unsigned int i;
  int r1 = rand();
  int r2 = rand();
  for(i = 0; ; i++) {
    if (r1 == r2) {
        printf("Oops. rand() = %d; i = %d\n", r1, i);
    }
    r1 = r2;
    r2 = rand();
  }
  return 0;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)