什么是const修饰词的目的

什么是const修饰词的目的

本文介绍了什么是const修饰词的目的,如果我可以通过在C指针修改呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  Does邪恶的施法得到由邪恶的编译器莫须有?

您好,

如果我可以通过指针修改一个恒定的,那么什么是它的目的是什么?
下面是code:

If I can modify a constant through a pointer, then what is the purpose of it?Below is code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
 const int a = 10;
 int *p = (int *)&a;

 printf("Before: %d \n", a);
 *p = 2;
 /*a = 2; gives error*/

 printf("After: %d \n", *p);

 return 0;
}

OUTPUT:

OUTPUT:

在:10结果
  后:2结果
  preSS任意键继续。 。 。

使用Visual Studio 2008。

Using Visual Studio 2008.

推荐答案

您可以修改值的原因是因为你做了指针的类型转换是扒掉常量内斯

The reason you could modify the value is because you did a pointer typecast that stripped off the constness:

int *p = (int *)&a;

这类型转换一个 const int的* (即&放大器;一个)到 INT * ,让您自由修改的变量。通常情况下,编译器会警告你这一点,但明确的类型转换燮pressed警告。

This typecasts a const int* (namely &a) to an int *, allowing you to freely modify the variable. Normally the compiler would warn you about this, but the explicit typecast suppressed the warning.

背后在所有的常量的主要理由是prevent您意外修改的东西,你答应不。这并不是神圣不可侵犯的,正如你所看到的,你可以抛弃常量毫无顾忌内斯,远在你可以做其他的不安全之类的指针转换为整数同样的方式或相反亦然。我们的想法是,你不应该尽力让自己乱用常量,编译器会警告你,如果你这样做。当然,加入了石膏告诉编译器:我知道我在做什么,等你的情况上面并没有产生任何形式的警告。

The main rationale behind const at all is to prevent you from accidentally modifying something that you promised not to. It's not sacrosanct, as you've seen, and you can cast away constness with impunity, much in the same way that you can do other unsafe things like converting pointers to integers or vice-versa. The idea is that you should try your best not to mess with const, and the compiler will warn you if you do. Of course, adding in a cast tells the compiler "I know what I'm doing," and so in your case the above doesn't generate any sort of warnings.

这篇关于什么是const修饰词的目的,如果我可以通过在C指针修改呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 22:52