Home > Software engineering >  Why does '5' '9' give 110?
Why does '5' '9' give 110?

Time:09-07

I am studying C. How is this answer 110?

   #include <stdio.h>
   void main()

    {
         char c1,c2,sum ;
         c1='5';
         c2='9';
         sum= c1 c2;
         printf("sum=%d",sum);

    }

CodePudding user response:

The character '5' has an ascii value of 53.
The character '9' has an ascii value of 57.

53 57 == 110.

CodePudding user response:

First things first:

  1. The type char in C can be used in two ways, depending on how one uses it:

    i. It can store small integer values (up to 255 if treated as unsigned or [-128,127] if treated as signed) [1]. So one can use it to do arithmetic operations, provided they are careful with overflow.

    ii. (Integer) values stored as chars can be used to represent "characters" (i.e. alphanumeric symbols), which are used when displaying messages.
    How does this representation work? The value of the char variable is looked upon the ASCII table, and the symbol that has the specific value is printed out.
    Note: This "functionality" is "optional": Char's are treated like integers throughout the code (case i.) and only when you invoke some function like putchar(), printf("%c", ...) this conversion happens and your code never actually "sees" it.

  1. The single quotes in C are something similar to an operator: When you write a (single) character within single quotes, the compiler does the ASCII translation backwards; it takes that character, searches for it on the ASCII table, and returns the (integer) value that represents that character. So '5' essentially returns an integer value of 53 (and '9' has an ASCII value of 57).

Using the above, then we observe that:

char c1 = '5';
char c2 = '9';

is equivalent to

char c1 = 53;
char c2 = 57;

only that in the first case, the compiler does the conversion for you so that you don't have to remember every value.

From then on, using the fact that char is an integer type,

char sum = c1   c2; 

gives sum the value of 53 57=110.

One thing to note here: sum, being a char can also be used to print out a symbol using the ascii table. In fact, 110 corresponds to the symbol for n. So if the code had the line

printf("%c\n", sum);

or

putchar(sum);

The letter n would be printed on the screen.
This trick of adding/subtracting ASCII values to get to other values can be used in a few ways like converting lowercase to uppercase, converting numeric values to their actual integer values (e.g. from '5' to get 5), and so on.


[1] A char variable uses 1 byte (i.e. 8 bits) to store its values. So it can store 2^8 = 256 values.

  •  Tags:  
  • c
  • Related