Doubts about storing values in a variable

0

I'm having trouble understanding this 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 , ie I should only store numbers, strong> 'test' The program works normally, so I probably missed something or I'm not understanding how variables in c work, so if anyone can please explain or point me in the direction , so I can understand why this happens.

    
asked by anonymous 16.11.2017 / 05:08

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 this case, when you call getchar , you are asking for something from the default input that internally the function returns with one-byte information. In the description of the function it even speaks of why an integer is the return:

  EOF, which indicates failure

Free translation:

  

The return type is int to accommodate for the special value EOF , which indicates failure

In general, C works without much concern about integer data types, converting from one to the other indiscriminately. When the conversion is from a type of smaller size to a larger size, the type is said to have undergone an integer promotion .

The putchar function 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.

Translating stays:

  

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

So what happened here that worked right in your code is that the character received by the standard input has undergone an entire promotion internally before being returned by getchar . So you passed the promoted value forward to the putchar function, which expects exactly one promoted value, and then converts it to an unsigned character and prints it.

    
16.11.2017 / 05:23