0

Possible Duplicate:
int c = getchar()?

#include <stdio.h>

   main()
   {
       int c;
       c = getchar();
       while (c != EOF) {
           putchar(c);
           c = getchar();
       }
   }

I dont have experience with C but i know C++ .I want to ask that 'c' here is declared as an integer type but surprisingly when i run this program , it accepts even characters . Can anyone kindly explain .

Ref : C programming Ritchie/kernighan

Community
  • 1
  • 1
  • In C, char type can know as integer or character :) When use `char variable` as integer, it will print ordinary number of its character in table. and when use as char, it will print as character – hqt Nov 29 '12 at 19:55
  • 'i know C++' -- Apparently not, since this code works identically in C++. – Jim Balter Nov 29 '12 at 21:10

2 Answers2

2

it accepts even characters

Actually, getchar() returns int, so no problem here.

Even if it returned char, since both char and int are integral types of the same signedness and int is wider than char, an int can always store a char using an implicit conversion (sometimes it's called an "upcast", but it's not really a cast, since it's implicit). Basically what this means is

int n = 'a';

is perfectly valid C.

1

First, getchar returns an int, not char.

Second, char is widened to an int at assignment.

MByD
  • 135,866
  • 28
  • 264
  • 277