Justin Chan
Justin Chan

Reputation: 49

C programming -storing characters into ints?

#include <stdio.h>
int main (void)
{
    int c;
    while ( (c = getchar ()) != EOF )
        putchar (c);

    return 0;
}

So in this program, there is c = getchar (). So i would assume that getchar returns to an integer regardless of what you type?

If that was the case, if I had the code:

#include <stdio.h>
int main (void)
{
    char c;
    c = getchar();
    printf("%c",c);

    return 0;
}

It should not work. As if I typed 'y' for example, the getchar function can return to an integer that is 2digits or more and cannot be stored in a char variable. Yet it worked.... In fact, when I type 'f' c becomes f. But why??

Upvotes: 2

Views: 80

Answers (2)

chux
chux

Reputation: 153348

So in this program, there is c = getchar (). So i would assume that getchar returns to an integer regardless of what you type?

True. Detail: int getchar() returns not any integer but an int. The return value is either in the unsigned char range (example 0 ... 255) or EOF. EOF is a negative value.


char c = getchar();
printf("%c",c);

... should not work. As if I typed 'y' for example, the getchar function can return to an integer that is 2 digits or more and cannot be stored in a char variable. Yet it worked.... In fact, when I type 'f' c becomes f. But why??

If the user types y, the typical reuslt is a valueof 121 (ASCII y). The int in not "2 digits or more". The int is a value store in memory, typical 32-bits. It is not store as "digits".

The printf("%c",c); accepts an int as to match the "%c". As a char, c goes though integer promotion (to an int) before being passed to printf(char *format, ...) all it well specified.

The following will typically all print the same. "%c" recieves the int value, converts it to an unsigned char and then print the corresponding character associate with that value. usually ASCCI y.

char c = 'y';
printf("%c", c);
printf("%c", 'y');
printf("%c", 121);
printf("%c", 121 + 256);

Upvotes: 0

Arkku
Arkku

Reputation: 42129

Characters are integers, or rather there are contexts where certain integer values are interpreted as characters. The type char is just an integer type in C, so an int can hold all values of a char.

One reason why getchar returns an int is because the special value EOF is not any of the integer values that represent characters (because if it were, you could not distinguish end of file from such a character being input). Once you have checked that the value returned by getchar was not EOF, all other possible return values are characters.

Upvotes: 2

Related Questions