I have the code like this :
#include <stdio.h>
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
The C documentation says that the getchar() returns the int value. And in the above program we have assigned c type as an int. And most importantly EOF is a integer constant defined in the header function.
Now if the code changes to something like this:
#include <stdio.h>
main()
{
char c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
This code also works! Wait a min, as per C documentation getchar() returnsint, but see in the above code I’m storing it in char. And C compiler doesn’t throw any error. And also in while loop I have compared c which is an char with EOF which is an int and compiler doesn’t throw any error and my program executes!
Why does the compiler doesn’t throw any error in the above two cases?
Thanks in advance.
No. It simply means that the returned value which is an
int, implicitly converts intochartype. That is all.The compiler may generate warning messages for such conversion, as
sizeof(int)is greater thansizeof(char). For example, if you compile your code with-Wconversionoption with GCC, it gives these warning messages:That means, you should use
intto avoid such warning messages.