I've seen this done in C before:
#define MY_STRING "12345"
...
#define SOMETHING (MY_STRING + 2)
What does SOMETHING get expanded to, here? Is this even legal? Or do they mean this?:
#define SOMETHING (MY_STRING[2])
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With