1

I am using Ubuntu 12.04 LTS with gcc. Can anyone tell me, how can this character type variable hold more than one byte? NOTE : This program will echo all characters(more than one) you type. For instance, if u type "thilip", then it will echo as "thilip". each character holds 8-bits(one byte), so i have typed 6 character (6 bytes). Then, How can getchar function assign this value to character type variable which can hold only one byte?

#include <stdio.h>
int main(void)
{
    char ch;

    while ((ch = getchar()) != '#')
        putchar(ch);

    return 0;
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 2
    And the proof that it holds more than one byte? – digital_revenant Oct 20 '13 at 18:12
  • 1
    @thilip Are you wondering how `ch` which is of `char` type (one byte) can get output values of `getchar` which is `int`? There is implicit `int -> char` cast in your code. – Igor Popov Oct 20 '13 at 18:15
  • 1
    Kunal, This program will echo all characters(more than one) you type. For instance, if u type "thilip", then it will echo as "thilip". each character holds 8-bits(one byte), so i have typed 6 cahracter (6 bytes). Then, How can getchar function assign this value to character type variable which can hold only one byte? – thilip kumar Oct 20 '13 at 18:25
  • "linux 12.04" God dammit! – Guido Oct 20 '13 at 18:28
  • Your `ch` is called a "variable" for a reason... you can change it's value, so over time it can hold many different chars, one at a time. – hyde Oct 20 '13 at 18:35

3 Answers3

2

It can't. Every time getchar is called, its previous value is overwritten with the new one.

damienfrancois
  • 52,978
  • 9
  • 96
  • 110
1

char type variable is of 1 Byte. You can check it by

printf("%zu", sizeof(char));  

If you are wondering that on giving input

asdf  

it is printing

asdf  

because of ch holds this asdf then you are wrong. getchar() reads only one character at a time.
When you input multiple char's then this set of character gets stored in input buffer. Then, getchar() reads a character one by one from this input buffer and assign one character at a time to the char variable ch, and putchar() prints it one by one. After each iteration ch is overwritten by the new character read by getchar().
You can check that getchar() reads only one char at a time by running this code

#include <stdio.h>

int main(void)
{
    char ch;
    ch = getchar();
    putchar(ch);

    return 0;
} 

Input:

thilip  

Output:

t  

Side note:

getchar() returns int. You should declare ch as int.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

It is one byte. What makes you think it's not?

pajton
  • 15,828
  • 8
  • 54
  • 65
  • Characters like U+2026(which is '…') have _two_ bytes of data within them. And some can have more. – Someone Dec 28 '20 at 00:15