Questions about storing values in a variable

Asked

Viewed 65 times

0

I’m having trouble understanding this particular while loop:

#include <stdio.h>

main()
{
    int c;

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

The result of an execution is this:

$ ./teste 
teste
teste
teste1
teste1
teste2
teste2
teste3
teste3

As you can see I declared 'c' as being a variable of type int, i.e., should store only numbers, but when providing input to string 'test' the program works normally, so I probably missed something or am not understanding as variables in c work, so if anyone can please explain or point me in the direction, so that I can understand why this happens.

1 answer

0


In , a variable of type char is an integer of only a single byte. Whether it will be interpreted graphically or numerically will depend on the context.

In case, when calling getchar, you are asking for something from the standard input that internally the function returns with one byte information. In the description of the function he even speaks of why an integer is the return:

The Return type is int to accommodate for the special value EOF, which indicates Failure

In free translation:

The type of return is int to accommodate for the special value EOF, indicating failure

Generally speaking, C works without much concern about the whole data types, converting from one to the other indiscriminately. When the conversion is from a type of smaller to larger size, it is said that the type has suffered a whole promotion.

The function putchar says the following about your argument:

The int Promotion of the Character to be Written.
The value is internally converted to an unsigned char when Written.

That translating gets:

The promotion int of the character to be written.
The value is internally converted to a unsigned char when written.

So, what happened here that worked in your code is that the character received by the standard entry underwent an entire promotion internally, before being returned by getchar. Then you passed the promoted value forward to the function putchar, that expects exactly a promoted value and then converts it to a no-signal character and prints it.

  • In the second paragraph, you said "standard input that internally returns the function with one byte information", which you meant by "one byte information"?

  • From here, signed char: of the same size as char, an integer between [-128, 127]; unsigned char: of the same size as char, an integer between [0, 255]. You only need one byte to store the information. In this case, the value 257 is the EOF to indicate end of reading

Browser other questions tagged

You are not signed in. Login or sign up in order to post.