type casting in C doesnt change 97 to 'a'
Solution 1:
97
, 0x61
and 'a'
are just different ways of producing the same int
value (at least on an ASCII-based machine).
And char
is just another integer type, so casting the value to a char
isn't going to help.
To print that value as a
, use %c
.
#include <stdio.h>
int main(void) {
printf("%d\n", 97); // 97
printf("%d\n", 'a'); // 97
printf("%c\n", 97); // a
printf("%c\n", 'a'); // a
}
Solution 2:
In the second call you are trying to output a character as an integer using the conversion specifier %d
.
printf("%d\n", (char)(97));
Instead you could just write using the conversion specifier %c
printf("%c\n", 97);
In this case the casting is not required.
Pay attention to that even if you will write
printf("%c\n", (char)(97));
or
char c = 'a';
printf("%c\n", c);
nevertheless the second argument expression will be promoted to the type int
due to the integer promotions.
Also in C integer character constants like 'a'
have the type int
.
Solution 3:
#include<stdio.h>
int main(){
printf("%d\n", (int)('a'));
printf("%c\n", (char)(97));
}
char
is an integral type (same as int
, long
, long long
etc etc), only ranges are different.
%d
printf integer, character constant 'a'
has type int
and value 97
in ASCII
.
You do not need casts in your example:
#include<stdio.h>
int main(){
printf("%d\n", 'a');
printf("%c\n", 97);
}