Difference between “implicit declaration of function” and the original version of the function

十年热恋 提交于 2019-12-25 01:58:01

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!