Difference between int and char in getchar/fgetc and putchar/fputc?

后端 未结 2 727
北荒
北荒 2020-11-21 11:22

I am trying to learn C on my own and I\'m kind of confused with getchar and putchar:

1

#include 

int main(v         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 11:55

    Always use int to save character from getchar() as EOF constant is of int type. If you use char then the comparison against EOF is not correct.

    You can safely pass char to putchar() though as it will be promoted to int automatically.

    Note: Technically using char will work in most cases, but then you can't have 0xFF character as they will be interpreted as EOF due to type conversion. To cover all cases always use int. As @Ilja put it -- int is needed to represent all 256 possible character values and the EOF, which is 257 possible values in total, which cannot be stored in char type.

提交回复
热议问题