1
I saw on another forum that guy subtracted -48 from one char
and the char
became a whole, because it happened?
#include<stdio.h>
int main(){
char num='3';
printf("%d",num-48);
return 0;
}
1
I saw on another forum that guy subtracted -48 from one char
and the char
became a whole, because it happened?
#include<stdio.h>
int main(){
char num='3';
printf("%d",num-48);
return 0;
}
7
Chars are actually integers, which are a table code ASCII, so if you subtract a number from it, you change the value of your code.
for example:
#include<stdio.h>
int main(){
char num='3';
printf("%d",num-48);
return 0;
}
would print the number 3, because the character value '3'
is 51 in the ASCII table, and 51-48 = 3.
you can do this "trick" for both numbers and alphabet characters:
//imprime: a b c, d e f
printf("%c %c %c, %c %c %c", 'a', 'a'+ 1, 'a'+ 2, 'f'-2, 'f'-1, 102);
//imprime 0, 0
printf("%d, %d", 'a'- 97, 'A'- 65);
/imprime 47
printf("%d%d",'4'- 48, '7'- 48);
for this just use the value of the first "element" of the set of the table you want, or any other you want to use, as base / reference point.
Just one observation: They are not necessarily from the ASCII table, although it is one of the most common.
6
It does not turn whole, or everything is an integer. This code does not show that it has become an integer.
C is a weak typing language, so all values can be interpreted as best suits you. The code has to interpret the constant value in the variable num
as if it were an integer decimal type, this is determined by the %d
, if you use a %c
will be printing the representation of this number as a character.
The stored number exists by itself, you can give several textual representations to it on demand.
This code better demonstrates what happens:
#include<stdio.h>
int main() {
char num = '3';
printf("|%c|%d|%c|%d|", num - 48, num - 48, num, num);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Browser other questions tagged c char
You are not signed in. Login or sign up in order to post.
The char type is already an integer, usually 8 bits in size; whether it is 'Signed char' or 'unsigned char', depends on the architecture. Since the C language has automatic promotion, %d expects an integer of type 'int' but can accept short int and char.
– epx