#include<stdio.h>
int main()
{
int i = 577;
printf("%c",i);
return 0;
}
After compiling, its giving output "A". Can anyone explain how i'm getting this?
CodePudding user response:
%c
will only accept values up to 255 included, then it will start from 0 again !
577 % 256 = 65; // (char code for 'A')
CodePudding user response:
577 in hex is 0x241. The ASCII representation of 'A'
is 0x41. You're passing an int
to printf
but then telling printf
to treat it as a char
(because of %c
). A char
is one-byte wide and so printf
looks at the first argument you gave it and reads the first byte. Since your computer's architecture is little-Endian, that first byte is the least significant byte which is 0x41.
To print an integer, you need to use %d
or %i
.
CodePudding user response:
The program has undefined behavior and doesn't have to output A
. It happens to do so in your case since %c
makes it take one byte (from the stack most likely) and it found that part of an int
which happend to represent an A
. The leftovers from the int
you placed there corrupts the stack.
CodePudding user response:
Just output the value of the variable i
in the hexadecimal representation
#include <stdio.h>
int main( void )
{
int i = 577;
printf( "i = %#x\n", i );
}
The program output will be
i = 0x241
So the least significant byte contains the hexadecimal value 0x41
that represents the ASCII code of the letter 'A'
.