about “int const *p” and “const int *p ”

后端 未结 8 2000
無奈伤痛
無奈伤痛 2020-12-09 00:11
#include 
using namespace std;

int main(int argc, char* argv[])
{
    int i1 = 0;
    int i2 = 10;

    const int *p = &i1;
    int const *p2 =          


        
8条回答
  •  眼角桃花
    2020-12-09 00:31

    const int *p = &i1;
    int const *p2 = &i1;
    

    These both declare non-const pointers to const data.

    That is, using p, you cannot change the data it points to. However, you can change the pointer itself, for example, by assigning as p = &i2 which is legal. But *p = 87987 is illegal, as the data p points to is const!

    --

    int * const p = &i1;
    

    This declares const pointer to non-const data. That is, p=&i2 is illegal, but *p = 98789 is legal.

    --

    const int * const p = &i1;
    

    This declares const pointer to const data. That is, now both p=&i2 and *p=87897 are illegal.

提交回复
热议问题