Reputation: 21
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;
}
Upvotes: 1
Views: 769
Reputation: 67747
'9'
and 9
are both integer constants.
'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
There are other coding conventions and standards (like EBCDIC), but it is very unlikely nowadays to work on the machine which uses them
Upvotes: 5
Reputation: 71
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.
Upvotes: 1
Reputation: 20272
'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.
Upvotes: 1