Home:ALL Converter>When and why const_cast is necessary for converting non-const to const types?

When and why const_cast is necessary for converting non-const to const types?

Ask Time:2020-05-10T19:59:37         Author:Roma

Json Formatter

  • When and why const_cast is necessary for converting non-const to const types?

  • Why in the following code const-cast is necessary for line 8 and unnecessary for lines 6, 7, 9?

int a = 27;                                     // 1
int const b = 412;                              // 2
int* pa = &a;                                   // 3
int const c = a;                                // 4
int d = b;                                      // 5
int const* p1 = pa;                             // 6
int* const* p2 = &pa;                           // 7
int const** p3 = const_cast<int const**>(&pa);  // 8
int const* const* p4 = &pa;                     // 9

Please answer both questions or provide a link to the explanation:)

Author:Roma,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/61711603/when-and-why-const-cast-is-necessary-for-converting-non-const-to-const-types
yy