I saw in another forum that the guy subtracted -48 from a char and the char became an integer, did that happen?
#include<stdio.h>
int main(){
char num='3';
printf("%d",num-48);
return 0;
}
I saw in another forum that the guy subtracted -48 from a char and the char became an integer, did that happen?
#include<stdio.h>
int main(){
char num='3';
printf("%d",num-48);
return 0;
}
Chars are actually integers, which are a code from the ASCII table, 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;
}
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);
To do this simply use the value of the first "element" of the table set that you want, or any other one that you want to use, as a base / reference point.
It does not become whole, or everything is an integer. This code does not show that it has become an integer.
C is a poor typing language, so all values can be interpreted as best suits you. The code tells you 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
you will be sending 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 best demonstrates what happens:
#include<stdio.h>
int main() {
char num = '3';
printf("|%c|%d|%c|%d|", num - 48, num - 48, num, num);
}