问题
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?
回答1:
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 (a double
actually). sleep
will interpret the bit representation of this double
as an int
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 an int
with rounding to 0.
来源:https://stackoverflow.com/questions/16361006/difference-between-implicit-declaration-of-function-and-the-original-version-o