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

后端 未结 8 1992
無奈伤痛
無奈伤痛 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:40

    Succinctly; each combination of read/write int & pointer;

    int main() {
    
      int a,b;
    
      int* w;                       // read/write int, read/write pointer
      w= &b;                        // good
      *w= 1;                        // good
    
      int* const x = &a;            // read only pointer, read/write int 
      // x = &b;                    // compilation error
      *x = 0;                       // good
    
      int const * y;                // read/write ptr, read only int 
      const int * y2;               // "    "    "
      y = &a;                       // good
      // *y = 0;                    // compilation error
      y2 = &a;                      // good
      // *y2 = 0;                   // compilation error
    
      int const * const z = &a;     // read only ptr and read only int 
      const int * const z2 = &b;    // "    "   "   "   
      // *z = 0;                    // compilation error
      // z = &a;                    // compilation error
      // *z2 = 0;                   // compilation error
      // z2 = &a;                   // compilation error
    
    }   
    

提交回复
热议问题