What does '9' mean in C?

385 views Asked by At

When writing '9' instead of 9 as my char c my endresult becomes negative and wrong for some reason. Why is that? What does '9' do?

#include <stdio.h>

int main() {
    int a, b;
    char c = '9';
    a = 44;
    b = a - c;

    printf("%d \n", b);

    return 0;
}
3

There are 3 answers

0
littleadv On

'9' is a representation of 57, which is the index at which the glyph 9 shows up in the ASCII table. As such, a-c equals to 44-57, which yields the negative result.

0
GebaiPerson On

char a = '9' means a's value is the ascii code of the character 9, , which is 57 instead of the value 9.

So b = a - c is actually 44 - 57.

10
0___________ On

'9' and 9 are both integer constants.

  • 9 has integer value of nine
  • '9' - has integer value of the (usually) ASCII code of symbol '9'. It is 57 It is for our convenience when we deal with strings and characters.
    char c = '9';
    int a = 44;
    int b = a - c;
  • char is also integer type having size 1 (sizeof(char) is by definition 1) Variable c has integer value of 57.
  • c is being converted to int and it is subtracted from a (44-57). The result is assigned to b

ASCII table: enter image description here

There are other coding conventions and standards (like EBCDIC), but it is very unlikely nowadays to work on the machine which uses them