Why can C compile time () without its library?

When I use the time() function (i.e. just rank the sample for rand() ), but does not include the time.h header file, 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, because time.h not 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 this related to the gcc version or just the difference between C / C ++?

+7
c ++ c gcc g ++
source share
2 answers

You must enable <time.h> for time (2) and enable warnings. In C, a function without a visible prototype is supposed to return int (which was deprecated since C99). Therefore, compiling with gcc seems fine, but g++ doesn't.

Compile with:

 gcc -Wall -Wextra -std=c99 -pedantic-errors file.c 

and you will see that gcc also complains about this.

+7
source share

C89 / C90 (usually, but incorrectly, called "ANSI C") has an "implicit int " rule. If you call a function without a visible declaration, the compiler will effectively create an implicit declaration, assuming that the function takes type arguments that appear in the call and returns an int .

The time function takes an argument of type time_t* and returns a value of type time_t . Therefore, when calling

 time(NULL) 

without a visible declaration, the compiler will generate the code as if it took an argument of type NULL (which is likely to be int ) and returns an int result. Considering,

 srand(time(NULL)) 

the value returned by time(NULL) will then be implicitly converted from int to `unsig

If int , time_t and time_t* all, say, 32 bits, most likely it will work. If they have different sizes,

+1
source share

All Articles