I've seen this done in C before:
我以前在C中见过这种情况:
#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])
2 个解决方案
#1
81
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
#2
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.
当你有一个数组或指针时,p+x等于&p[x]。MY_STRING + 2等价于&MY_STRING[2]:它生成字符串中第三个字符的地址。
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会发生什么。MY_STRING + 0与&MY_STRING[0]是相同的,两者都与只写MY_STRING相同,因为字符串引用仅仅是字符串中第一个字符的指针。令人高兴的是,身份操作“添加0”是一个禁止操作。考虑到这是一种心理单元测试,我们可以用它来检验“+”的意思是否正确。
#1
81
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
#2
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.
当你有一个数组或指针时,p+x等于&p[x]。MY_STRING + 2等价于&MY_STRING[2]:它生成字符串中第三个字符的地址。
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会发生什么。MY_STRING + 0与&MY_STRING[0]是相同的,两者都与只写MY_STRING相同,因为字符串引用仅仅是字符串中第一个字符的指针。令人高兴的是,身份操作“添加0”是一个禁止操作。考虑到这是一种心理单元测试,我们可以用它来检验“+”的意思是否正确。