Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allowed to static_cast between different types of const?

Tags:

c++

I have rarely seen static_cast between top level const so far.
Recently I had to use static_cast to display address of a pointer to const object and I come out with this question:
Is it allowed to static_cast between different types of const?

It passed compilation using gcc 4.7. But I am just asking here to confirm it is not UB. Thanks.

  const int a = 42; // test case 1, const obj
  const double b = static_cast<const double>(a);
  cout << b << endl;


  const int c = 0; // test case 2, pointer to const obj
  cout << static_cast<const void*>(&c) << endl;
like image 592
Minteh Avatar asked Dec 09 '25 20:12

Minteh


1 Answers

From [expr.static.cast]

[...] The static_cast operator shall not cast away constness

It's perfectly fine to add const using static_cast, then again you don't need to in your test case

const int a = 42; // test case 1, const obj
const double b = static_cast<double>(a); // Works just as well.
const double b = a; // Of course this is fine too

I suppose one of the few times you'd want to add const with static_cast would be to explicitly call an overloaded function

void foo(int*) { }
void foo(int const*) { }

int main()
{
  int a = 42;

  foo(&a);
  foo(static_cast<int const*>(&a));
}

Although with properly designed code you shouldn't really need to do this.

like image 169
user657267 Avatar answered Dec 11 '25 09:12

user657267



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!