const_cast and const pointer to const vaiable - c++

How is it possible that the value of *p and the value of DIM are different but the have the same address in memory?
const int DIM=9;
const int *p = &DIM;
* (int *) p = 18; //like const_cast
cout<< &DIM <<" "<< p << '\n';
cout << DIM << " " << *p << '\n';

You're changing the value of a const variable, which is undefined behavior. Literally anything could happen when you do this, including your program crashing, your computer exploding, ...
If a variable is supposed to change, don't make it const. The compiler is free to optimise away accesses to const variables, so even if you found a successful way to change the value in memory, your code might not even be accessing the original memory location.

It is a compiler optimization. Given that DIM is a constant, the compiler could have substituted its known value.

The code below does what you meant to do... as mentioned in other posts, if you mean to change the value of an variable, do not define it as const
#include <stdio.h>
int main()
{
int d= 9;
int *p_d=&d;
*p_d=18;
printf("d=%d\np_d=%d\n",d,*p_d);
return 0;
}
This code prints
d=18
p_d=18

Related

Why a reference declaration influences my pointer?

Case 1
#include <iostream>
using namespace std;
int main() {
int n = 1;
// int & r = n;
int * p;
cout << &n << endl;
cout << p << endl;
return 0;
}
Output 1
0x7fffffffdc94
0
Case 2
#include <iostream>
using namespace std;
int main() {
int n = 1;
int & r = n;
int * p;
cout << &n << endl;
cout << p << endl;
return 0;
}
Output 2
0x7fffffffdc8c
0x7fffffffdd90
In Output 2, the pointer p just pointed to the address followed int n. Shouldn't an unintialized pointer point to some random places?
Why adding a reference declaration influences the address of p pointed to?
Shouldn't an unintialized pointer point to some random places?
No, an uninitialized pointer points nowhere. It has an indeterminate value. Trying to read and/or print this indeterminate pointer value as you are doing in
cout << p << endl;
has undefined behavior. That means there is no guarantee whatsoever what will happen, whether there will be output or not or whatever the output will be.
Therefore, there is no guarantee that changing any other part of the code doesn't influence the output you will get. And there is also no guarantee that the output will be consistent in any way, even between runs of the same compiled program or multiple compilations of the same code.
Practically, the most likely behavior is that the compiler will emit instructions that will simply print the value of whatever memory was reserved on the stack for the pointer. If there wasn't anything there before, it will likely result in a zero value. If there was something there before it will give you that unrelated value.
None of this is guaranteed however. The compiler can also just substitute the read of the pointer value with whatever suits it or e.g. recognize that reading the value has undefined behavior and that it may therefore remove the output statement since it can not be ever reached in a valid program.

Why can't assign const initialize while compile by pointer

I'm curious about why my research result is strange
#include <iostream>
int test()
{
return 0;
}
int main()
{
/*include either the next line or the one after*/
const int a = test(); //the result is 1:1
const int a = 0; //the result is 0:1
int* ra = (int*)((void*)&a);
*ra = 1;
std::cout << a << ":" << *ra << std::endl;
return 0;
}
why the constant var initialize while runtime can completely change, but initialize while compile will only changes pointer's var?
The function isn't really that relevant here. In principle you could get same output (0:1) for this code:
int main() {
const int a = 0;
int* ra = (int*)((void*)&a);
*ra = 1;
std::cout << a << ":" << *ra;
}
a is a const int not an int. You can do all sorts of senseless c-casts, but modifiying a const object invokes undefined behavior.
By the way in the above example even for std::cout << a << ":" << a; the compiler would be allowed to emit code that prints 1:0 (or 42:3.1415927). When your code has undefinded behavior anything can happen.
PS: the function and the different outcomes is relevant if you want to study internals of your compiler and what it does to code that is not valid c++ code. For that you best look at the output of the compiler and how it differs in the two cases (https://godbolt.org/).
It is undefined behavior to cast a const variable and change it's value. If you try, anything can happen.
Anyway, what seems to happen, is that the compiler sees const int a = 0;, and, depending on optimization, puts it on the stack, but replaces all usages with 0 (since a will not change!). For *ra = 1;, the value stored in memory actually changes (the stack is read-write), and outputs that value.
For const int a = test();, dependent on optimization, the program actually calls the function test() and puts the value on the stack, where it is modified by *ra = 1, which also changes a.

const_cast<double*> works but const_cast<int*> doesn't

My problem is, why first part of the code does not work while the second one works. Non-const pointer should modify the const value using the const_cast previously but with integers this trick does not work. Could you explain why that happens?
const int i = 5;
cout << i << endl; //output: 5
int *ptr_i = const_cast<int*>(&i);
*ptr_i = 100;
cout << i << endl; //output : 5
const double d = 5;
cout << d << endl; //output : 5
double *ptr_d = const_cast<double*>(&d);
*ptr_d = 100.;
cout << d << endl; //output : 100
Modifying a const variable is undefined behaviour:
n4296 ยง7.1.6.1/4
Except that any class member declared mutable (7.1.1) can be modified,
any attempt to modify a const object during its lifetime (3.8) results
in undefined behavior.
const_cast is generally for communicating with non-const-correct APIs or casting away volatile qualifiers; it shouldn't be used like this.
Non-const pointer should modify the const value using the const_cast previously but with integers this trick does not work.
No, non-const pointer modifying the const value is undefined behavior. It is not supposed to work.
Could you explain why that happens?
Since this is UB, the compiler is free to do anything at all here, and "anything at all" means the code will happen to work in the case of int only (at least, for your compiler).
TLDR: undefined behavior is undefined.

Cannot Convert from const int* to int*

I'm trying to compile the following piece of code, but I'm getting a C2440 (visual studio) error. I've tried looking at other resources for help, but I can't find a good explanation.
int main()
{
int a = 100;
SomeFunction(&a);
}
void SomeFunction(const int* value)
{
//This line of code gives me the error.
int* variable = value;
cout << "Value is " << *Variable << " end" << endl;
}
I know I can solve this problem by using int* variable = const_cast<int*> (value);, but I still don't understand why the above code is causing a problem.
The error's quite clear - a pointer conversion can't remove a const qualifier; otherwise, you could violate the constness:
int* variable = value; // Not allowed - but if it were...
*variable = 42; // BOOM! changed a constant.
If you don't want to be able to change the value being pointed at, then keep it const
const int* variable = value;
If you do want to change it, then don't make it const in the first place:
void SomeFunction(int* value)
I know I can solve this problem by using const_cast
That's a bad idea - you'll get undefined behaviour if you abuse const_cast and try to modify a constant object. You should use const where you can, but not when you want to modify something.
The const int* means that you have the address of an int that you are not allowed to change.
An int* can be used to change the int it points to. Clearly that violates the above statement that you aren't allowed to change it.
const_cast does not actually "solve the problem". It lets you request to change something which cannot be changed. Such an attempt can cause your program to fail in uncontrolled ways (formally, undefined behavior). In your particular example, the variable a in main is not const, and so const_cast will successfully change it. But that creates close coupling and contradicts the promise made by a function whose signature is const int*.
int* variable = value; is wrong.
It should be,
int variable = *value
and
cout << "Value is " << variable << " end" << endl;
const int * means that the function guarantees that value at this address will not change, but if you can do:
int * variable = value;
Then you can also do
*variable=30;
In doing so, the guarantee of function that is of const pointer will be harmed.

Passing a temp pointer to a temp pointer to an object

#include <iostream>
#include <tchar.h>
void output(int *param)
{
std::cout << "Value: " << *param << std::endl;
};
int _tmain(int argc, _TCHAR* argv[])
{
int i = 34;
output(&i);
return 0;
}
obviously writes "Value: 34" to the console.
But if I make the following changes
...
void output(int **param)
{
std::cout << "Value: " << **param << std::endl;
}
...
output(&(&i));
...
I get a compile error "'&' requires l-value".
By the way, I even tried to make the following change:
output(&34);
Indeed this feels wrong ... somehow.
My question is: Why is this not allowed to use & at an r-value? Is there some reason on assembler level?
You are trying to get a reference to a r-value and that is basically not defined, since it is always a temporary value and actually never has an address on the stack/heap. That is why C++11 introduced r-value references, but that is a totally different subject to your question.
To get your code to compile your need to do the following:
int i = 34;
int* pi = &i;
output(&ip);
By "grounding" your reference in pi, you give the compiler a real address on the stack that can be given to output.
You're trying to get the address of an address, and an address is not an l-value. (You can very roughly think about l-values as values that can stand on the left side of an operation. Variables, and "named values" are l-values, for example)
Store the first address somewhere.
int number = 4;
int* firstAddress = &number;
int** secondAddress = &firstAddress;
output(secondAddress);