Not including stdlib.h does not produce any compiler error!

前端 未结 5 1199
太阳男子
太阳男子 2020-12-11 08:33

Hopefully this is a very simple question. Following is the C pgm (test.c) I have.

#include 
//#include 

int main (int argc,          


        
5条回答
  •  不思量自难忘°
    2020-12-11 09:02

    C, unfortunately, does not require functions to be prototyped (or even declared) before use -- but without a prototype, it automatically makes certain assumptions about the function. One of those is that it returns an int. In your case, atoi does return an int, so it works correctly. atof doesn't, so it doesn't work correctly. Lacking a prototype/declaration, you get undefined behavior -- typically it'll end up retrieving whatever value happens to be in the register where an int would normally be returned, and using that. It appears that in your particular case, that happens to be a zero, but it could just as easily be something else.

    This is one of the reasons many people push "C++ as a better C" -- C++ does require that all functions be declared before use, and further that you specify the types of all (non-variadic) parameters as well (i.e. a C++ function declaration is like a C prototype, not like a C declaration).

提交回复
热议问题