1

I'm looking at some code regarding scheduling with QueryPerformanceFrequency. I can't understand what's going on here. Why is the rvalue wrapped in parenthesis? A LARGE_INTEGER is a struct, so initializing would require {} instead, but totally confused by this line. QueryPerformanceFrequency returns a bool, too.

// Initialize the resolution of the timer
LARGE_INTEGER Timer::m_freq = (QueryPerformanceFrequency(&Timer::m_freq), Timer::m_freq);

The header contains a Timer struct with a private member:

static LARGE_INTEGER m_freq;
bobbay
  • 483
  • 4
  • 9
  • 1
    It's the comma operator. It's also being badly abused. – Raymond Chen Jul 21 '16 at 19:42
  • 2
    Wow. Initializing a variable to be equal to itself. I wonder if that's even legal? – Harry Johnston Jul 21 '16 at 22:35
  • The usual advice about iffy coding practices is to treat whomever is going to have to maintain your code some day as a homicidal maniac who knows where you live. Clearly the problem here is that you don't have an address. We don't know either. – Hans Passant Jul 21 '16 at 22:58
  • @HarryJohnston [Does initialization entail lvalue-to-rvalue conversion? Is `int x = x;` UB?](http://stackoverflow.com/q/14935722/995714), but a comma introduces a sequence point so I'm not sure in this case – phuclv Jul 22 '16 at 04:59

1 Answers1

1

It's bad. Just bad as the commenters have said.

Given that QueryPerformanceFrequency should be a cheap call to make, there's little need to cache it as a global (static) variable.

Do this instead.

  1. Remove the static declaration from the m_freq variable in the class declaration.

  2. Initialize m_freq in the constructor of your Timer class.

Example:

Timer::Timer()
{
    BOOL result = QueryPerformanceFrequency(&m_freq);

    if (result==FALSE)
    {
        // optional - set error condition.  But it's not like
        // the original code was handling the potential error either
    }
}
selbie
  • 100,020
  • 15
  • 103
  • 173