Without including #include <ctype.h>

北战南征 提交于 2019-12-23 11:50:31

问题


I have written the below programs without including #include <ctype.h>. I am able to execute the program. Where are these prototypes declared? I am using gcc.

1.

#include <stdio.h>
int main()
{
    if(isalnum(';'))
        printf("character ; is not alphanumeric");
    if(isalnum('A'))
        printf("character A is alphanumeric ");
    return 0;
}

2.

#include <stdio.h>
int main()
{
    printf("Lower case of A is %c \n", tolower('A'));
    printf("Lower case of 9 is %c \n", tolower('9'));
    printf("Lower case of g is %c \n", tolower('g'));
    printf("ASCII value of B is %d \n", toascii('B'));
    printf("Upper case of g is %c \n", toupper('g'));
    return 0;
}

回答1:


  1. In your code these functions are implicitly declared, so they are not included from any particular header. If you crank up warning level for your compiler, you will see (e.g. GCC):

    $ gcc -Wall -o a.c
    a.c: In function ‘main’:
    a.c:4: warning: implicit declaration of function ‘isalnum’
    

    If the definition of the function is not available, the compiler assumes i's a function taking any number of arguments and returning int. For example, the following compiles:

    main(){fgetc(1,2,3,4,5);}
    
  2. As to where they should be declared, it's the <ctype.h> header. Of course, different C implementations may include this header in other headers, so the code may appear to work without including <ctype.h>, but if you want your code to compile without warnings across different C implementations, you should include this header.




回答2:


A function doesn't need to be declared to be used (but I'd expect modern C compiler to give a warning in such cases) if it is used with the correct argument. It is as if the function had be declared

int isalnum();

(and not

int isalnum(...);

which isn't C -- one need at least one named paramater -- and if it was variadic functions may use a different calling convention than non variadic one).

This is possible only for function returning int and having parameters which are not touched by promotion (char and short are touched by promotion; functions from the standard library often are in this class for historical reason).



来源:https://stackoverflow.com/questions/4645982/without-including-include-ctype-h

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