I use gcc4.8. And I wrote such code, using sleep.
int main(int argc, char *argv[])
{
/* I know it's worong to pass a floating number to sleep
* this is only for testing. */
sleep(0.001);
return 0;
}
I compile it with "gcc -Wall a.c -o a", got warning "implicit declaration of function ‘sleep’ [-Wimplicit-function-declaration]". Then I ran it, this program sleeps approximately 1 second (it seems sleep ceils 0.001 to 1).
Then I change the code to be like this:
#include <unistd.h> /* add header file */
int main(int argc, char *argv[])
{
/* I know it's worong to pass a floating number to sleep
* this is only for testing. */
sleep(0.001);
return 0;
}
This time it only sleeps 0 second, seems like sleep floors 0.001 to 0.
Shouldn't these two sleep be identical?
In the first (wrong) case a real floating point value is given to sleep as it is assumed that the prototype of
sleep
takes a floating point value (adouble
actually).sleep
will interpret the bit representation of thisdouble
as anint
and wait for so many seconds. You are lucky that this is only 1 second. In the second case the floating point value is cast to anint
with rounding to 0.