3

The codes compiles without error, but time is declared nowhere.

Fortunately, the error has been gone as I changed the name as mtime. But what is the nature of the error is? What is time?

The output of this program is 1. I wonder if there is anything called time in the file iostream or somewhere.

#include <iostream>
int main()
{
    std::cout << time << std::endl;
    return 0;
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Zhang Kai
  • 33
  • 4
  • 2
    Probably the [`std::time`](http://en.cppreference.com/w/cpp/chrono/c/time) function, or rather its C-equivalent [`time`](http://en.cppreference.com/w/c/chrono/time). A pointer to a function will be seen as a boolean value that is always true, and `true` will without manipulators or setting flags in `std::cout` be printed as `1`. – Some programmer dude Oct 06 '17 at 09:41
  • What is you platform and what is your compiler? – Jabberwocky Oct 06 '17 at 09:43

5 Answers5

6

It is the address of a time_t time(time_t*) function as your <iostream> implementation includes the time.h header. The address will never be NULL and is implicitly convertible to boolean hence the result of 1. You are probably using g++ on Linux.

Ron
  • 14,674
  • 4
  • 34
  • 47
2

My suspect is that it's the time_t time(time*) function, whose operator<< best match is the one taking a bool (a function pointer is just an implicit conversion away from a bool). Now, given that it's a function pointer pointing to an actual valid function, it is converted as true, which is then printed as 1 (the default if the boolalpha flag is not set is to print booleans as 0/1).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
0

There is std::time, but that shouldn't be the case, since std is not the namespace used.

So, it has to be this function:

time_t time (time_t* timer);

which has to be included implicitly by iostream header.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

C++ standard library functions are defined in namespace std. For instance, <ctime> header is required to provide std::time function. But in practice this functionality is provided by underlying C library where there is no concept of namespaces. So, C++ standard library headers are allowed to also define certain functions in global namespace.

A quote from C compatibility headers section in cppreference:

including <cstdlib> definitely provides std::malloc and may also provide ::malloc. Including <stdlib.h> definitely provides ::malloc and may also provide std::malloc.

So, for instance, time function may happen to be defined in global namespace after a standard library header is included. This is allowed by standard but is implementation specific.

dewaffled
  • 2,850
  • 2
  • 17
  • 30
0

I've found a question Why does iostream include time.h? verifying the answers above and explaining the reason for the function's appearing. It's really the work of function time_t time(time_t * timer) :)

Zhang Kai
  • 33
  • 4