-3

In the code below, if I enter 11(1 and 1), the output is:[]1. [] part is not garbage, I just used the symbols("[]") to express the empty output. Therefore the real output is just 1 with one empty space if front of 1.

int main(void)
{
   int x = 1;

   char y = 1;

   x = getchar();
   y = getchar();
   x = x - x;
   putchar(x);
   putchar(y);
}

In addition, if I replace x = x - x; to

x -= 3;

and enter 11 or 22, it gives me output like *1 or /2.

Why is this happening?

Thank you.

Tom_the_cat
  • 159
  • 12
  • 3
    What are you expecting to happen? –  Aug 07 '18 at 02:04
  • 2
    What character is ASCII 0? – Lee Taylor Aug 07 '18 at 02:06
  • 2
    x and y will hold the ASCII encoding of whatever value you have entered. So, when you enter `11`, both x and y will hold the ASCII encoding if 1, which is the integer '49'. For the code above with `x = x - x`, that will leave the zero, which is the NULL character in x. So, putchar wouldn't print anything. So, if you subtract 3 from 49, you get 46 which is the ASCII encoding for `.`, and that's what putchar would output in this case. – bruceg Aug 07 '18 at 02:07
  • To be pedantic, the C Standard places few restrictions on character encodings that may be used in an implementation, and does not require ASCII. One of the restrictions is that the null character `\0` (or sometimes abbreviated `NUL`) has a value of 0, regardless of the actual encoding used. This character is used to terminate strings in C. EBCDIC is another encoding that has been used in implementations, but much less common these days. UTF-8 contains ASCII as a subset, and is probably the actual encoding used on your system. In all of these encodings the null character has a value of 0. – ad absurdum Aug 07 '18 at 12:37

1 Answers1

0

You have to think in terms of ASCII values. When you perform x = x - x, you're saying x = 0 (the ascii code for whatever character I type in for x minus itself is always 0)

Then look up 0 in the ASCII table, and you'll see null. So it will print null (looks like a space) and a 1.

When you perform x -= 3;, you're taking the numeric ascii code for the character you typed in, and subtracting 3. If you look at the ASCII table, you'll notice that 3 characters before the character 1 is * and three characters before 2 is /. This explains the results you are getting.

If you intend to convert the characters into the numeric values it represents, there is a bunch of ways to do this, you can subtract '0' or use the atoi function after converting the char to a string in C.

-'0' method

int numeric = x - '0';

atoi method requires a conversion to string.

char str[2] = "\0";
str[0] = x;
int numeric = atoi(str);

Both these will not make sense if you typed in a non-numeric character, e.g. aa