0
#include<stdio.h>
int main(){
    printf("%d\n", (int)('a'));
    printf("%d\n", (char)(97));
}

Why does the program above give the output

97
97

instead of

97
a
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Matthias
  • 1
  • 1
  • you're printing in %d, just print %c. You don't even need to cast for that. – Asphodel Jan 20 '22 at 18:39
  • `%d` tells printf to print the decimal representation of the corresponding parameter and `97` is strictly equivalent to `'a'`. Try `printf("%c\n", 97)` and `printf("%c\n", 'a')`. The `()` casts are useless, the have no effect here. – Jabberwocky Jan 20 '22 at 18:39
  • If you want to see the output `a` you need format `%c` instead of `%d`. `%d` expects a value of type `int`. – Bodo Jan 20 '22 at 18:39

5 Answers5

1
#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);
}
0___________
  • 60,014
  • 4
  • 34
  • 74
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
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Because you need write %c, not %d in the last line.

printf("%d\n", (char)(97));

to

printf("%c\n", 97);
Degik
  • 19
  • 5
0

What you want is printing a character, but in your second printf call you specify format %d instead of %c, then printf output your (char)(97) as an integer.

Stone
  • 1