0

I tried to seed the rand() function

Why do I always get the same sequence of random numbers with rand()?

#include "stdafx.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <windows.h>
#include <string> 
#include <shlobj.h>
#include <Shlwapi.h>
#include <stdio.h>
#include <aclapi.h>
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <curl/curl.h>
#include <future>
#include <stdlib.h>
#include <random>
#include <ctime>
#include <time.h>  
#include <Lmcons.h>
srand(time(NULL)); 
int random_integer = std::rand(); 

But srand(time(NULL)) returned:

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

error C2365: 'srand' : redefinition; previous definition was 'function'

Community
  • 1
  • 1
user10056
  • 63
  • 4
  • 12

1 Answers1

3

The problem right now is that the call srand(time(NULL)); needs to go inside a function -- at global scope, you can't just write code that will execute -- you can only declare/define functions, variables, etc.

Definitions can include initializers, which is what allows the int random_integer = std::rand(); to work.

One obvious cure:

int radom_integer;

int main() { 
    srand(time(NULL));
    random_integer = rand();
    // ...
}

That said, you're generally better off using the C++ random number generator classes than srand/rand.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 3
    And the misleading error message is caused by the compiler trying (and failing) to figure out what `srand(time(NULL));` means in that context. It doesn't consider that it could be a (non-declaration) statement, because statements are not permitted outside function bodies. The closest guess it can make is that it's a malformed function declaration with a missing return type (which, in old-style C, would have been implicitly of type `int`). – Keith Thompson Sep 13 '13 at 04:32