[LEAPSECS] Lets get REAL about time.

Clive D.W. Feather clive at davros.org
Sun Jan 22 10:42:16 EST 2012


Poul-Henning Kamp said:

>>> #define timespecsub(vvp, uvp) \

>>> do { \

>>> (vvp)->tv_sec -= (uvp)->tv_sec; \

>>> (vvp)->tv_nsec -= (uvp)->tv_nsec; \

>>> if ((vvp)->tv_nsec < 0) { \

>>> (vvp)->tv_sec--; \

>>> (vvp)->tv_nsec += 1000000000; \

>>> } \

>>> } while (0)

>>>

>>> Lovely, isn't it ?

>> Unlovely, but not the ugliest, especially considering that there may

>> not have been a better way at the time.

>> The 'do { ... } while (0)' kludge is at least as ugly as its contents[...]

> The do {...} while(0) is the least ugly way to make function-like CPP

> macros safe for below average programmers IMO.


For below-average programmers to write, perhaps. The obvious way for a
competent programmer to write this without that horrible hack is:

#define timespecsub(vvp, uvp) \
((vvp)->tv_sec -= (uvp)->tv_sec, \
(vvp)->tv_nsec -= (uvp)->tv_nsec, \
((vvp)->tv_nsec < 0) \
? ((vvp)->tv_sec--, (vvp)->tv_nsec += 1000000000) \
: (void) 0)

This has the advantage of being usable wherever a function can appear.

Of course, since it evaluates its arguments multiple times, the usual
convention is to put the name in uppercase.

But with a modern compiler I'd just write it as a function (possibly an
inline one) and let the compiler worry about efficiency.

--
Clive D.W. Feather | If you lie to the compiler,
Email: clive at davros.org | it will get its revenge.
Web: http://www.davros.org | - Henry Spencer
Mobile: +44 7973 377646


More information about the LEAPSECS mailing list