What's the point of const pointers?

后端 未结 17 1919
粉色の甜心
粉色の甜心 2020-11-30 17:28

I\'m not talking about pointers to const values, but const pointers themselves.

I\'m learning C and C++ beyond the very basic stuff and just until today I realized t

17条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 18:00

    If you do embedded systems or device driver programming where you have memory mapped devices then both forms of 'const' are often used, one to prevent the pointer from being reassigned (since it points to a fixed hardware address.) and, if the peripheral register it points to is a read-only hardware register then another const will detect a lot of errors at compile time rather than runtime.

    A read-only 16 bit peripheral chip register might look something like:

    static const unsigned short *const peripheral = (unsigned short *)0xfe0000UL;

    Then you can easily read the hardware register without having to resort to assembly language:

    input_word = *peripheral;

提交回复
热议问题