This is very specific, and a bit difficult to explain, and quite likely impossible, but here goes. Perhaps some C cracks out there have an idea...
I want to implement <errno.h>. (My hobby project is implementing a Standard C library.)
The naive way to go about it is:
// in <errno.h>
extern int errno;
// in some .c file
int errno = 0;
This works. But it has one disadvantage: If a math library function is called, it always has to query the FPU status after execution to set errno as appropriate. This stalls the FPU in math-heavy applications.
The C standard endorses lazy evaluation of errno by making it a macro instead:
int * __errno();
#define errno *__errno()
This way, errno is only "set" when its value is actually requested:
// "__errno()" returns the location of the current errno value,
// the "errno" macro turns it into a value.
x = errno;
Given some logic in the rest of the library, the FPU status needs only be queried if the last library function called was actually one using the FPU, and the value of errno is actually requested.
So far, everything is fine. But it's the other way around that is giving me headaches:
errno = 0;
The value of errno is not requested at all. But __errno() does not know that, and will query the FPU status if the last library function called was using the FPU.
Right now I don't see a way to avoid that (i.e., have the errno macro or the __errno() function somehow work differently depending on whether they are used to the left or the right of the assignment operator), and am almost content to accept this.
But perhaps any of you SO'ers has a brilliant idea?