Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: expected delcaration specifiers or '...' before 'time' [C]

Tags:

c

time

gcc

ubuntu

I have a simple function that is giving me this error:

error: expected delcaration specifiers or '...' before 'time'

here is the code in the file:

#include <stdlib.h>
#include <time.h>

srand(time(NULL));

float random_number(float min, float max) {
    float difference = (max - min);
    return (((float)(difference + 1)/RAND_MAX) * rand() + min);
}

i dont get why im getting this error. I'm compiling with gcc in Ubuntu 12.04.

like image 788
user2917393 Avatar asked Jan 12 '23 23:01

user2917393


2 Answers

In the C language, all code that is executed at runtime must be inside a function. Put the call to srand() inside an init function.

like image 79
Lundin Avatar answered Jan 14 '23 12:01

Lundin


You cannot have call to functions outside the main function scope, also, there is no sense in seeding random just before you use it in function random_number

you need to move srand(time(NULL)); to main function, like:

float random_number(float min, float max) {
    float difference = (max - min);
    return (((float)(difference + 1)/RAND_MAX) * rand() + min);
}

int main()
{
    srand(time(NULL));
    // your code which calls random_number here
}

another approach, do not change main, but:

static int isRandomInited = 0;
float random_number(float min, float max) {
    if (!isRandomInited) { // init random only 1 time
        srand(time(NULL));
        isRandomInited = 1;
    }
    float difference = (max - min);
    return (((float)(difference + 1)/RAND_MAX) * rand() + min);
}
like image 27
Iłya Bursov Avatar answered Jan 14 '23 13:01

Iłya Bursov