Null pointer in C++

前端 未结 8 633
悲&欢浪女
悲&欢浪女 2021-01-14 20:02

When in C++ I declare a null pointer to be int* p=0, does that mean the zero is some special constant of integer pointer type, or does it mean that p

8条回答
  •  长情又很酷
    2021-01-14 20:37

    Yes. Zero is a special constant. In fact, it's the only integral constant which can be used, without using explicit cast, in such statements:

    int *pi = 0;  //ok
    char *pc = 0; //ok
    void *pv = 0; //ok
    A *pa = 0;    //ok
    

    All would compile fine.

    However, if you use this instead:

    int *pi = 1;  //error
    char *pc = 2; //error
    void *pv = 3; //error
    A *pa = 4;    //error
    

    All would give compilation error.

    In C++11, you should use nullptr, instead of 0, when you mean null pointer.

提交回复
热议问题