0

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.

4
  • 1
    ctime returns a char*, i.e. a pointer to a string buffer. The function does not have to be thread safe. Therefore the same buffer might be reused. You should print the first result before you call again. Also: You only compare buffers, not string content. At least when it comes to C which you have tagged your question with. Commented Oct 22, 2021 at 13:18
  • This is clearly not C. Commented Oct 22, 2021 at 13:21
  • @Gerhardh I'm using C++, updated tags. Sorry for the confusion. Commented Oct 22, 2021 at 13:22
  • You want to use ctime_r(3) with two different preallocated buffers Commented Oct 22, 2021 at 14:06

1 Answer 1

4

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.

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

2 Comments

that and ... << ctime(&m_start_time) << " " << ctime(&m_end_time) << "\n"; prints the same string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.