Devesh Lohumi
Devesh Lohumi

Reputation: 388

Why does ctime returns the same string for different time_t values?

I have a function which prints time_t values.

void Logger::describe()
    {
        cout << m_start_time << " " << m_end_time << "\n";
            if (ctime(&m_start_time) == ctime(&m_end_time))
            {
                cout << "check1\n";
            }
            cout << m_vehicle->getPlate() << " " << ctime(&m_start_time) << " " << ctime(&m_end_time) << "\n";
    }

// m_start_time and m_end_time are private variables of type time_t of the class Logger

For a sample output after waiting a couple of seconds I get

1634907786 1634907791
check1
bike1 Fri Oct 22 18:33:06 2021
 Fri Oct 22 18:33:06 2021

As can be seen m_start_time and m_end_time are different but ctime returns the the same value. Can anyone help explain why ?

I'm using gcc 6.3.0 if it helps.

Upvotes: 0

Views: 224

Answers (1)

Passerby
Passerby

Reputation: 958

Read the information on the return value here: ctime

It is a pointer to a static string. You are not comparing the string content (see strcmp), only this pointer.

Upvotes: 4

Related Questions