0

I have a very simple c++ source like this:

#include <iostream> int main() { srand(time(NULL)); } 

I am using g++ to compile like this :

g++ ./test.cpp 

but it successfully compiles despite the fact that time() function is defined in ctime and it is not included with #include

my professor at university runs the code with visual studio (vc++) but he is unable to run the code without including ctime

Am I missing something here ?

by the way my g++ version is :

g++ (Ubuntu 11.2.0-7ubuntu2) 11.2.0

4
  • 4
    Standard headers are allowed to include other standard headers. Don't rely on this. Always include headers you need Commented Dec 14, 2021 at 6:41
  • 1
    on a side note for C++ random, have a look at the <random> header file. (srand is IMO a bit of a "C" left over) Commented Dec 14, 2021 at 6:44
  • @RemyLebeau yes.final conclusion is exactly what you said.but it can be misleading for a new c++ programmer! Commented Dec 14, 2021 at 7:27
  • @PepijnKramer yes you are right . actually this c++ code is translated from a c counterpart ! Commented Dec 14, 2021 at 7:28

1 Answer 1

0

first of all explicitly include what you need,
(thanks to darkblueflow for pointing it out)
secondly #include order matters,

believe or not they can shadow declaration, just switch if first case doesn't work

#include <cstdlib> #include <ctime> // differs from #include <ctime> #include <cstdlib> // in some aspects 

your best shot is to include headers explicitly and keep this in mind this good luck

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.