What does “12345” + 2 do in C?

后端 未结 2 1501
独厮守ぢ
独厮守ぢ 2020-12-30 22:05

I\'ve seen this done in C before:

#define MY_STRING \"12345\"
...
#define SOMETHING (MY_STRING + 2)

What does SOMETHING get expand

相关标签:
2条回答
  • 2020-12-30 22:20

    When you have an array or pointer, p+x is equivalent to &p[x]. So MY_STRING + 2 is equivalent to &MY_STRING[2]: it yields the address of the third character in the string.

    Notice what happens when you add 0. MY_STRING + 0 is the same as &MY_STRING[0], both of which are the same as writing simply MY_STRING since a string reference is nothing more than a pointer to the first character in the string. Happily, then, the identity operation "add 0" is a no-op. Consider this a sort of mental unit test we can use to check that our idea about what + means is correct.

    0 讨论(0)
  • 2020-12-30 22:25

    String literals exist in the fixed data segment of the program, so they appear to the compiler as a type of pointer.

    +-+-+-+-+-+--+
    |1|2|3|4|5|\0|
    +-+-+-+-+-+--+
     ^ MY_STRING
         ^ MY_STRING + 2
    
    0 讨论(0)
提交回复
热议问题