#include<stdio.h>
void main()
{
int n = 2;
printf("%c",&n);
}
Output: L
On using %d
it of course gives the address of variable n
but why is it outputting L on using %c
?
#include<stdio.h>
void main()
{
int n = 2;
printf("%c",&n);
}
Output: L
On using %d
it of course gives the address of variable n
but why is it outputting L on using %c
?
It is undefined behaviour because you have used wrong format specifier.
C11 Standard: 7.21.6.1 : paragraph 9:
If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
It means anything can happen if printf
is called with a wrong format specifier.
As the other answer of rsp said the behaviour is undefined and anything could happen.
In your case the following happens:
It reads one byte of &n
because a character is of one byte size which is mostly 8 bits long, see CHAR_BIT
explanation on SO. Then it prints it as character.
This byte could be the first byte of &n
if the types int*
and int
are the same at your machine. That would mean that your variable n
lies at address 0x48...
(big-endian) or 0x...48
(little-endian) as 0x48
is H
in the Ascci code. I assume that your program is using Ascii for encoding which doesn't necessarily have to.
(You changed the character from H
to L
but I leave this answer as it is.)
Also this byte can lie somewhere in the middle of the &n
if an int*
exceeds the size of an int
at your system.
You should compile with more warnings enabled for example -Wall
in gcc and you will get:
warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
In the case you cast that value to a char
the behaviour will be well defined but rely on the implementation as a cast of a pointer type to an integer is implementation defined.
Nevertheless what you're doing makes no sense also with a cast it will not do.
It's because you told printf() function to show the first 1-byte of int n's address as a char.