为什么 C 可以在没有其库的情况下编译 time()?

Why can C compile time() without its library?

当我使用 time() 函数(即只是随机化 rand() 的种子)但不包含头文件 time.h 时,它适用于 C。例如:

#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;
}

当我尝试编译上面的代码时,g++ 无法编译它,因为 time.h 不包含在内。但是 gcc 可以。

$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));
                ^

它与 gcc 版本有关还是只是 C/C++ 之间的区别?

您应该为 time(2) 添加 <time.h> 并打开警告。在 C 中,没有可见原型的函数被假定为 return int(自 C99 以来已弃用)。所以用 gcc 编译似乎没问题,而 g++ 却不行。

编译:

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

你会看到 gcc 也抱怨它。

C89/C90(通常但不正确地称为 "ANSI C")有一个 "implicit int" 规则。如果你调用一个没有可见声明的函数,编译器会有效地创建一个隐式声明假设函数接受调用中出现的类型的参数并且returnsint.

time 函数采用 time_t* 类型的参数和 returns time_t 类型的值。所以给了一个电话

time(NULL)

没有可见的声明,编译器将生成代码 ,就好像 它采用了 NULL 类型的参数(很可能是 int) 和 returns 一个 int 结果。鉴于

srand(time(NULL))

然后 time(NULL) 返回的值将从 int 隐式转换为 `unsig

如果 inttime_ttime_t* 都恰好是 32 位,那么调用可能会起作用。如果它们的尺寸不同,