How is the following line interpreted by GCC compiler:
printf("HELLO");
I want to know this because when I am running following program:
main()
{
printf(5+"Good Morning");
}
The program is printing:
Morning
Why is the compiler is starting the printing from the sixth character?
There are a lot of things happening here. As others have said,
printf()doesn’t ‘know’ anything about the expression5+"Good Morning". The value of that expression is determined by the C language.First,
a+bis the same asb+a, so5+"Good Morning"is the same as"Good Morning"+5.Now, the type of
"Good Morning"(i.e., a string literal) is an “array ofchar“. Specifically,"Good Morning"is a 13-character array (12 “regular” characters, followed by a0). When used in most expressions, the type of an array in C “decays” to a pointer to its first element, and binary addition is one such case. All this means that in"Good Morning"+5,"Good Morning"decays to a pointer to its first element, which is the characterG.Here is how the memory looks like:
The value of the address of
Gplus 5 is a pointer that points to 5 locations fromGabove, which isM. So,printf()is getting an address that is atM.printf()prints that till it finds a0. Hence you seeMorningas output.