Search code examples
cputchar

why x - x is nothing in putchar() in c language?


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.


Solution

  • 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