C/C++ 更改 const 的值
我有一篇文章,但我把它弄丢了.它展示并描述了一些人们应该小心的 C/C++ 技巧.其中一个对我很感兴趣,但现在我正在尝试复制它,我无法将它编译.?/p>
这个概念是可以在 C/C++ 中意外更改 const
的值
原来是这样的:
const int a = 3;//我保证我不会改变常量 int *ptr_to_a = &a;//我仍然保证我不会改变诠释*ptr;ptr = ptr_to_a;(*ptr) = 5;//我是个骗子;a 现在是 5
我想把这个给朋友看,但现在我错过了一步.有谁知道开始编译和工作缺少什么?
ATM 我得到从 'const int*' 到 'int*' 的无效转换,但是当我阅读这篇文章时,我尝试过,效果很好.
解决方案你需要抛弃 constness:
linux ~ $ cat constTest.c#include <stdio.h>无效 modA(int *x){*x = 7;}诠释主要(无效){常量 int a = 3;//我保证我不会改变诠释*ptr;ptr = (int*)( &a );printf("A=%d
", a);*ptr = 5;//我是个骗子,a 现在是 5printf("A=%d
", a);*((int*)(&a)) = 6;printf("A=%d
", a);modA( (int*)( &a ));printf("A=%d
", a);返回0;}linux ~ $ gcc constTest.c -o constTestlinux ~ $ ./constTestA=3A=5A=6A=7linux ~ $ g++ constTest.c -o constTestlinux ~ $ ./constTestA=3A=3A=3A=3
通用答案在 g++ 4.1.2 中也不起作用
linux ~ $ cat constTest2.cpp#include <iostream>使用命名空间标准;诠释主要(无效){常量 int a = 3;//我保证我不会改变诠释*ptr;ptr = const_cast<int*>( &a );cout <
顺便说一句.. 永远不推荐这样做...我发现 g++ 不允许这种情况发生.. 所以这可能是您遇到的问题.
I had an article, but I lost it. It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to replicate it I'm not being able to put it to compile.
The concept was that it is possible to change by accident the value of a const
in C/C++
It was something like this:
const int a = 3; // I promise I won't change a
const int *ptr_to_a = &a; // I still promise I won't change a
int *ptr;
ptr = ptr_to_a;
(*ptr) = 5; // I'm a liar; a is now 5
I wanted to show this to a friend but now I'm missing a step. Does anyone know what's missing for it to start compiling and working?
ATM I'm getting invalid conversion from 'const int*' to 'int*' but when I read the article I tried and it worked great.
解决方案you need to cast away the constness:
linux ~ $ cat constTest.c
#include <stdio.h>
void modA( int *x )
{
*x = 7;
}
int main( void )
{
const int a = 3; // I promisse i won't change a
int *ptr;
ptr = (int*)( &a );
printf( "A=%d
", a );
*ptr = 5; // I'm a liar, a is now 5
printf( "A=%d
", a );
*((int*)(&a)) = 6;
printf( "A=%d
", a );
modA( (int*)( &a ));
printf( "A=%d
", a );
return 0;
}
linux ~ $ gcc constTest.c -o constTest
linux ~ $ ./constTest
A=3
A=5
A=6
A=7
linux ~ $ g++ constTest.c -o constTest
linux ~ $ ./constTest
A=3
A=3
A=3
A=3
also the common answer doesn't work in g++ 4.1.2
linux ~ $ cat constTest2.cpp
#include <iostream>
using namespace std;
int main( void )
{
const int a = 3; // I promisse i won't change a
int *ptr;
ptr = const_cast<int*>( &a );
cout << "A=" << a << endl;
*ptr = 5; // I'm a liar, a is now 5
cout << "A=" << a << endl;
return 0;
}
linux ~ $ g++ constTest2.cpp -o constTest2
linux ~ $ ./constTest2
A=3
A=3
linux ~ $
btw.. this is never recommended... I found that g++ doesn't allow this to happen.. so that may be the issue you are experiencing.
相关文章