0

I know that we change const variable value this way in C(by changing it into non-const).

#include<stdio.h> 
#include<stdlib.h> 
int main() 
{ 
    const int var = 10; 

    int *ptr = &var; 
    *ptr = 5; 

    printf("var = %d\n", var); 

    return 0; 
} 

similar thing (using a pointer) in C++ gives me a compilation error

How can I update the const variable value in C++?

1 Answers1

5

Modifying a const value through any mechanism (including casting away const-ness) results in "undefined behavior" (UB) which means that you cannot reason about the behavior of the program. The compiler is allowed to assume that const values will never change. Based on that assumption, the compiler might:

  • Store const values in read-only memory pages; attempting assignment through the pointer would then cause an access violation.
  • Inline the const value wherever it is used. Because you take a pointer, the compiler will likely also emit some kind of storage for the value (on the stack most likely) so that it has a memory location that can be pointed to, but modifying this value will not cause the inlined values to change.
  • Something else, possibly including both of the above.

Which one it does can depend on the optimization level selected.

A program that assigns to a const value is effectively "nonsense" and has no meaningful interpretation.

Note that this is UB in both C and C++. You just need to twist the C++ compiler's arm a bit more to get the code to compile (int *ptr = const_cast<int *>(&var);). The C standard permits implicit discarding of a const qualifier in some contexts; the C++ standard is a lot more strict about this.

Most C compilers will emit a warning on int *ptr = &var; regarding discarding of the const qualifier. I would strongly recommend compiling with all warnings enabled and converted to errors (-Wall -Werror on gcc). That would cause the C compiler to also refuse to compile this code.


Note that casting const away from a pointer (or reference) and assigning to the target is not UB when the value was not declared const:

// non-const value
int x = 10;

// take a pointer to x and store it in a pointer-to-const
const int *y = &x;

// cast away the const-ness of the pointer target
int *z = const_cast<int *>(y);

// this is fine; z points at x which is not const
*z = 5;

However, if you find yourself needing const_cast then most likely you are either (1) doing some crazy template metaprogramming, or (2) approaching the problem wrong.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • 2
    I'll give you one better, and say that if it's not storing them in const pages, it's because it's inlining them in the assembly code itself. – Roguebantha May 21 '20 at 06:59
  • Also, I have another question, If a functions return type is const, what does it mean? – Ram Prabodh Induri May 21 '20 at 07:00
  • 1
    @RamPrabodhInduri There is no such thing in C++ as a const return value because that concept doesn't make sense. A function can return a _reference to a const value_ but this is something different. Can you give an example of some code where you think this is happening? – cdhowie May 21 '20 at 07:01
  • @Roguebantha Indeed, good point. I've added this to my answer. – cdhowie May 21 '20 at 07:06
  • 1
    @cdhowie my bad, i framed it wrong this is what i wanted to ask struct cmp { bool operator() (const pair &a, const pair &b) ***const*** { int lena = a.second - a.first + 1; int lenb = b.second - b.first + 1; if (lena == lenb) return a.first < b.first; return lena > lenb; } }; what does the const (the one with *** ) just before function description do in the following code, The code is a comparator function for user defined priority_queu in C++ – Ram Prabodh Induri May 21 '20 at 07:11
  • 2
    @RamPrabodhInduri That indicates that the member function `cmp::operator()` can operate on a `const cmp` object. The implicit `this` pointer within that member is effectively typed `const cmp *`. Functors are usually passed around either as const values or by reference-to-const, so without the `const` there, `operator()` could not be invoked on const `cmp` values or references thereto. – cdhowie May 21 '20 at 07:14
  • 2
    Or (3) [working with some legacy not const-correct system](https://stackoverflow.com/q/2673508/10957435). –  May 21 '20 at 07:24
  • @Chipster _(puts fingers in ears)_ LALALALALALA THOSE DON'T EXIST LALALALALALALA – cdhowie May 21 '20 at 07:26