开发者

How is printf statement interpreted?

开发者 https://www.devze.com 2023-01-08 15:34 出处:网络
How is the following line interpreted by GCC compiler: printf(\"HELLO\"); I want to know this because when I am running following program:

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 f开发者_开发问答rom the sixth character?


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.


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.


Is is the same as writing

char *ptr="Good Morning";

followed by

printf( ptr + 5 );

which is &ptr[5] this adress points to "Morning";

Adding an integer n to a pointer results to an adress ptr + n * sizeof(type)


Because "Good Morning" is a pointer to the string (actually to the first byte of it) and adding 5 to that pointer yields a pointer to the 5th character. C strings are null-terminated, so either way, printf runs until it encounters the null at the end.


It advances the input pointer by 5 bytes and hence skips the word "Good".

This is pointer arithmetic in C.

Lets assume base pointer of the string "Good Morning" is p, and 5+p =p+5 and it points to letter M.

Hence the input to printf is the pointer from the letter M.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号