Search code examples
c++c++11auto

How to declare a void pointer using auto?


We used to declare a void pointer like this without using auto.

void* ptr = nullptr;

How should we do the same thing using auto? Which one should we use? Or maybe there are other better ways?

auto ptr = (void*)nullptr;
auto ptr = (void*)0;

This is not a question about coding style. Just want to know IF we need to use auto, what should be the best way.


Solution

  • auto ptr = static_cast<void*>(nullptr);
    

    As you probably know, C style casts aren't so great since they will cast basically anything, while static_cast prevents both throwing away const, and crazy stuff reinterpret_cast allows.