Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to change const value in c++

Tags:

c++

constants

const value is often used in programming. It gives programmer security that the value will not change in future. Unfortunately, this is not fully enforced. As a consequence it sometimes causes subtle bugs that are very hard to decipher. As an example :

int a = 1;
const int& b = a; // I promise I will not change
a = 3; // I am a liar, I am now 3
cout << b; // As I will now show 3

It is possible to change const values in other ways also; some of them are quite complex and require good amount of code which often gets lost in other segment of code and hence causing bug.

Thus would anyone elaborate upon the possible ways to change a const value? Don't worry if you don't know all, many wouldn't (including myself). Just tell all of the ways you know - after all you can only give what you have!

like image 499
Existent Avatar asked Jun 08 '16 15:06

Existent


People also ask

How do you change a const value?

Changing Value of a const variable through pointer By assigning the address of the variable to a non-constant pointer, We are casting a constant variable to a non-constant pointer. The compiler will give warning while typecasting and will discard the const qualifier.

Can you modify a const?

No! You shouldn't modify a const variable. The whole point of having a const variable is to be not able to modify it. If you want a variable which you should be able to modify, simply don't add a const qualifier on it.

Can you change a const char in C?

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer. const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed.


1 Answers

const int& b = a; // I only promise I will not change the value via b, nothing more.

const doesn't guarantee the value won't be changed by other references or pointers. Think of the following code:

void f(const int& b) { ... }
...
int a = ...;
f(a);
a = ...;

The value of a won't be changed inside f() (by the passed argument), that's all the guarantee.

const is just a helper. If you won't change sth, then make it const, then compiler will help you to check it. You still could change the original value in other ways like your code showed, it's still your responsibility, finally.

like image 194
songyuanyao Avatar answered Sep 29 '22 15:09

songyuanyao