Printing ASCII value for characters.

I encountered a question on stackoverflow::

It says that if I have this scenario:

int i = 0;
printf("%lld", i);

Then this printf statement is undefined behaviour since the type specifier is wrong for the given int value.

But, since when we have to print the ASCII value of characters the first thing that we do is we use the statement ::

printf("%d", c);

where c is a char and we put this inside a while loop to print all the values.

So, is this undefined behaviour as well?? And we are using it without even knowing it??

you can also add two char and can make a new char or int accordingly by initializing to char or int. as:
int sum = ‘c’+‘d’;or int sum = 99 + 100; are same.
char s = ‘c’; or char s = 99; are same.

but won’t the printf statement mentioned will be undefined??

Here is the C program to print ASCII value of all alphabets. This program uses
printf(“ASCII value of %c = %d”,c,c); to print ASCII value.

long long int and int are same but there maximum sizes are diff.

int a=10;
printf("%lld",a);

this will definately work but the size matters.

in case of char, it is an integer type variable that has limits [0,255]

int a=65;
char c=a;

this will definately work and when you print this char with a %c it will print A, whereas if you print this with %d it will result to 65

so char can be used both as a character and integet datatype.

Hope you understand, else leave a comment.

:slight_smile:

DUDE DO THIS-
int main()
{
int i;
for(I=0;i<=255;i++)
{
printf("%d=%c",i,i);
}
return 0;
}

Passing to printf the wrong number of bytes is not a good Ideea. %lld requires a larger integer, in your case

printf("%lld", i);

here %lld taked as argument is wrong, since it would expect a 64-bit value.
Any way CHAR is just an integer type like INT, but this doesn’t mean that you can always use a CHAR as an INT. read about getchar() function where an INT is expected because of EOF which will not fit inside a CHAR.

To understand this concept one needs to know about about Implicit and Explicit Type-casting/conversion.
I advice you to go through this tutorial.

3 Likes
//