hi, i have a small problem with the rand operator. at first i tried using it without srand but gave me the same value each time.

i have inserted srand(time(0)); but my compiler throws me up these errors:

1>c:\users\ben\documents\university work\year 2\c++\code\myc++\spritelab\asteroidsgame.cpp(17): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\ben\documents\university work\year 2\c++\code\myc++\spritelab\asteroidsgame.cpp(17): error C2365: 'srand' : redefinition; previous definition was 'function'
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdlib.h(511) : see declaration of 'srand'

im not sure what they mean. my top bit of code looks like this:

#include "wrapGame.h"
#include <math.h>
#include <time.h>
#include <ctime>
#define PI 3.14159265
using namespace std;

srand(time(0));

im pretty sure this is right?

i also use the rand operator like this:

rand()%60;

any advice you can give would be great

You don't need both time.h and ctime. Just ctime is sufficient.

Are you defining a function srand() in your codefile asteroidsgame.cpp?

It also helps to typecast the return from time() to an unsigned int to make srand( ) happy.


Your use of rand() is OK, assuming you are looking for a value in the range 0-59, inclusive. If you want 1 to 60, add 1 to the result.

Edited 5 Years Ago by vmanes: n/a

i am defining srand() in the cpp file of my asteroids game yes. should i put it into the main file?

Your call to srand() cannot be put in the middle of nowhere like that. You need to put it inside a function body. The common options are at the very start of the main() function, or in the constructor of whatever class you have that needs rand().

EDIT: You should also include <cmath> instead of <math.h>, and only <ctime> not <time.h>.

Edited 5 Years Ago by mike_2000_17: n/a

1>c:\users\ben\documents\university work\year 2\c++\code\myc++\spritelab\asteroidsgame.cpp(17): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\ben\documents\university work\year 2\c++\code\myc++\spritelab\asteroidsgame.cpp(17): error C2365: 'srand' : redefinition; previous definition was 'function'
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdlib.h(511) : see declaration of 'srand'

Error #1:
This is coming because C++ expects the programmer to do the necessary typecast.
In you case you should have written
srand((int)time(0));

Error #2, #3:
You are calling the srand() function in global scope which is not allowed. Any statement should be enclosed inside a function (e.g inside main())
If you try to call it globally, the compiler will try to interprete as a new function declaration and srand() is already declared in "stdlib.h"

This question has already been answered. Start a new discussion instead.