2

According to documentation I checked, time_t time(time_t *seconds) is declared under <time.h> header file. Yet when I run this code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    srand(time(NULL));
    printf("%d",rand());
    return 0;
}

without including <time.h>,it works fine, or at least works. How does that happen?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
underdog
  • 31
  • 4
  • When you call a function without a prototype in scope it's like ... it's like sending a message to a stranger. You don't know if he understood it (maybe you wrote in English, but the stranger only understands Spanish) and you will not understand his answer. The prototype ensures the 'communication' goes smoothly. Note the stranger is always there (the function is in a library; the info is in the header file) whether you know his age, eye color, language... – pmg Dec 29 '20 at 07:53
  • 1
    [It cannot](https://godbolt.org/z/MTbcPx). The compiler is telling you that, loudly. If you decide to run a program that compiles with warnings, it's your own responsibility. If you are running a compiler that doesn't produce the warning, it's time to upgrade. See also [this](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings). – n. m. could be an AI Dec 29 '20 at 09:49

1 Answers1

6

It does not work fine, if you enable the compiler warnings. Without the required header, it'll throw a warning, something like

1347694184/source.c: In function ‘main’:
1347694184/source.c:7:11: warning: implicit declaration of function ‘time’ [-Wimplicit-function-declaration]
     srand(time(NULL));
           ^~~~

Moral of the story: Always use proper compiler settings to warn (and if possible consider warnings as errors). Take care of the warnings, and you'll be on the safer side.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261