How is printf statement interpreted?

后端 未结 5 1243
耶瑟儿~
耶瑟儿~ 2020-12-06 11:39

How is the following line interpreted by GCC compiler:

printf(\"HELLO\");  

I want to know this because when I am running following program

相关标签:
5条回答
  • 2020-12-06 12:11

    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.

    0 讨论(0)
  • 2020-12-06 12:11

    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 讨论(0)
  • 2020-12-06 12:16

    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.

    0 讨论(0)
  • 2020-12-06 12:27

    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.

    0 讨论(0)
  • 2020-12-06 12:32

    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)

    0 讨论(0)
提交回复
热议问题