Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is printf statement interpreted?

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?

like image 698
Mohit Avatar asked Jul 26 '10 06:07

Mohit


2 Answers

This is an artifact of C pointer-arithmetic; printf is just a red herring.

The type of a string literal (such as "Good morning") is const char *. Your code is equivalent to:

const char *p = "Good morning";
p = p + 5;
printf(p);

Adding a pointer and an integer produces a pointer to the 5th element in the sequence.

like image 82
Oliver Charlesworth Avatar answered Oct 16 '22 23:10

Oliver Charlesworth


There are a lot of things happening here. As others have said, printf() doesn't 'know' anything about the expression 5+"Good Morning". The value of that expression is determined by the C language.

First, a+b is the same as b+a, so 5+"Good Morning" is the same as "Good Morning"+5.

Now, the type of "Good Morning" (i.e., a string literal) is an "array of char". Specifically, "Good Morning" is a 13-character array (12 "regular" characters, followed by a 0). 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 character G.

Here is how the memory looks like:

  0   1   2   3   4   5   6   7   8   9   0   1   2
+---+---+---+---+---+---+---+---+---+---+---+---+---+
| G | o | o | d |   | M | o | r | n | i | n | g | 0 |
+---+---+---+---+---+---+---+---+---+---+---+---+---+

The value of the address of G plus 5 is a pointer that points to 5 locations from G above, which is M. So, printf() is getting an address that is at M. printf() prints that till it finds a 0. Hence you see Morning as output.

like image 38
Alok Singhal Avatar answered Oct 16 '22 21:10

Alok Singhal