C :使用Visual Studio编译器时const Pointers
C++: const pointers when using Visual Studio compiler
我对Visual Studio的C 编译器2012。
这只是一个测试代码,应该失败:
char s1[5] = "new";
char s2[5] = "old";
char const* p = s1;
p++; // should fail
p = s2; // this line should also fail;
有人可以告诉我,为什么起作用?
没有原因这些行应该失败。也许您将char const*
与char * const
混淆。在第一种情况下,char
S为const
。第二个指针是const
。在您的代码中,由于指针不是const
,因此可以同时执行p++
和p = s2;
。
记住规则:" const
适用于左侧,除非没有任何东西,在这种情况下,它适用于右边。"
const int x; // constant int
x = 2; // illegal - can't modify x
const int* pX; // changeable pointer to constant int
*pX = 3; // illegal - can't use pX to modify an int
pX = &someOtherIntVar; // legal - pX can point somewhere else
int* const pY; // constant pointer to changeable int
*pY = 4; // legal - can use pY to modify an int
pY = &someOtherIntVar; // illegal - can't make pY point anywhere else
const int* const pZ; // const pointer to const int
*pZ = 5; // illegal - can't use pZ to modify an int
pZ = &someOtherIntVar; // illegal - can't make pZ point anywhere else
ps:我从这里公然复制了此内容,我认为将来在这里也将在这里有用。
您认为增量应该不起作用,因为它是const char*
。但是,这里的const
指定无法修改的内容。并不是可以修改指针。
但是这是非法的。
char s1[5] = "new";
char s2[5] = "old";
char const* const p = s1;
^^^^
p++; // should not compile
p = s2;
C const
预选赛适用于左侧的左侧。否则,它适用于右侧的内容。
阅读此处有关const
正确性的更多信息。