[Solved] why the character value stores in integer? [duplicate]


The answer is in two parts.

You typed

c = getchar();

But getchar clearly returns characters, so how can this work? Well, actually, it works just fine, in part because the return value from getchar is actually an int (so that it can also return the non-char value EOF). So there’s no problem here at all.

And then how can you pass an int to get printed by %c? Normally when you call printf it’s important for the type of the argument you pass to properly match the type expected by the format specifier. (For example, it’s a real bug to pass an int and try to print it with %f.) But C doesn’t always pass types to functions exactly as you write them, sometimes they’re converted (“promoted”) to a larger, common type.

One of the times these conversions apply (and, in modern C, pretty much the only time) is when you’re calling a function that takes a variable number of arguments, like printf. In that case, when you pass an argument of type char or short int, it’s automatically upconverted to int. So printing an int value with %c is fine. (The other important promotion is that when you pass a float, it’s automatically converted to double. So it turns out you can print both float and double using %f.)

In fact, in C, characters really are small integers, so none of this is surprising. One way to see this is to change your printf call ever so slightly:

printf("I waited for the %d character\n", c);

Now if you type A, it’ll tell you it got 65, because in ASCII, the code for capital A is 65.

2

solved why the character value stores in integer? [duplicate]