How is printf statement interpreted?

后端 未结 5 1242
耶瑟儿~
耶瑟儿~ 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: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.

提交回复
热议问题