const char *允许改变字符值,为什么? [英] Const char * allowing to change the character value, why?

查看:201
本文介绍了const char *允许改变字符值,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

int main()
{
    char A = 'E';

    const char * i;

    i = &A;

    A = 'B';

}


不是const char *应该指向一个常量字符变量?为什么我可以将A更改为最后一行中的B?

which actually compiles with MSVC, why? Isn't a const char * supposed to point to a constant character variable? Why can I change A to 'B' in the last line?

我错过了什么?

推荐答案

指向 char 类型的常量和常量 char * 类型的指针。如果你想保护指针免受(意外)修改,你可以声明它的常量:

There is a difference between a constant of type char being pointed to (a.k.a. the pointee) and a constant pointer of type char*. If you want to protect a pointer from (accidental) modification, you can declare it constant:

char* p = '...';
char* const cp = 'Hello, World!'; // a constant pointer
cp[1] = ','; // okay, the pointee is not constant
cp = p;      // error, the pointer is constant

指向常量的变量指针可以改变:

A variable pointer to a constant can change:

char *p = '...';
const char* pc = 'Hello, World!'; // pointer to a constant
pc[1] = ','; // error, the pointee is constant
pc = p;      // okay

最后,可以用

const char* const cpc = 'Hello, World!';
cpc[1] = 'a'; // error, pointee cannot change
cpc = p;      // error, pointer cannot change

这是从C ++编程语言 ,Stroustrup。

This is from §5.4.1 of "The C++ Programming Language", Stroustrup.

您可以将 A 更改为'B'在最后一行,因为 A 是类型 char ,因此可以更改。它不会声明一个 const char ,这将阻止你这样做。

You can change A to 'B' in the last line, because A is of type char and therefore can be changed. It isn’t declared a const char, which would prevent you from doing so.

这篇关于const char *允许改变字符值,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆