Issue
When I use the time()
function (i.e., just randomize seed for rand()
) but not include the header file time.h
, it works for C. For example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
srand(time(NULL));
for(i=0;i<10;i++){
printf("\t%d",rand()%10);
}
printf("\n");
return 0;
}
When I try to compile the code above, g++
cannot compile it since time.h
isn't included. But gcc
can.
$gcc ra.c
$./a.out
4 5 2 4 8 7 3 8 9 3
$g++ ra.c
ra.c: In function ‘int main()’:
ra.c:8:20: error: ‘time’ was not declared in this scope
srand(time(NULL));
^
Is it related with version of gcc or just a difference between C/C++ ?
Solution
You should include <time.h>
for time(2) and turn on the warnings. In C, a function with no visible prototype is assumed to return int
(which has been deprecated since C99). So compiling with gcc
seems fine while g++
doesn't.
Compile with:
gcc -Wall -Wextra -std=c99 -pedantic-errors file.c
and you'll see gcc
also complains about it.
Answered By - P.P Answer Checked By - Willingham (WPSolving Volunteer)