Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"UnConsting" const value via pointer

Tags:

c++

First, sorry for possible question redundancy.

Doing some little experiments with C/C++ pointers in GCC I encountered this somewhat weird behaviour when bypassing constantness of value at the pointer address.

#include <iostream>
int main()
{
    using namespace std;

    const double number = 100;
//bypassing constantess of pointed-to value
    double * pointer_to_value = (double *) &number;
    *pointer_to_value += 200;

    cout << "Adress of number: " << &number << "\tValue of number: " << number << endl <<
    "   Pointer value: " << pointer_to_value << "\tDereferencing pointer: " << *pointer_to_value;

    return 0;
}

I would expect both form of checking the value yielding same results. Location of value is same in both cases. Program generates following output, however:

Adress of number: 0x22ff30 Value of number: 100 Pointer value: 0x22ff30 Dereferencing pointer: 300

Anyone capable of explaining? Thanks in advance.

like image 940
VarM Avatar asked Dec 04 '22 21:12

VarM


1 Answers

It's undefined behaivor.

It's irrelevant why exactly it happens (actually because the compiler inlines the value).

like image 127
Yakov Galka Avatar answered Jan 02 '23 06:01

Yakov Galka