const int* p, int* const p, const int* const p
in Cpp with 0 comment

const int* p, int* const p, const int* const p

in Cpp with 0 comment

const int p, int const p, const int* const p区别

时间久了难免会忘记,这里先记录一下。
我们以*为分界符,观察这些东西究竟是个什么玩意。

const int* p可以不带赋值初始化,之后可以指向一个普通int或者指向一个const int,不能通过*p去修改值,如果指向的是普通int的话直接用int的对象名改值就好。

下面随便贴几个测试。

#include <stdio.h> 
  
int main(){ 
    const int q = 5; 
    int const* p = &q; 
  
    //Compilation error 
    *p = 7; 
  
    const int q2 = 7; 
  
    //Valid 
    p = &q2;  
      
    return 0; 
} 
#include <stdio.h> 
  
int main(){ 
    const int q = 5; 
    //Compilation error 
    int *const p = &q; 
  
    //Valid 
    *p = 7;  
  
    const int q2 = 7; 
  
    //Compilation error 
    p = &q2;  
  
    return 0; 
} 
#include <stdio.h> 
  
int main(){ 
    const int q = 5; 
  
    //Compilation error 
    const int* const p = &q; 
  
    //Compilation error 
    *p = 7; 
      
    const int q2 = 7; 
  
    //Compilation error 
    p = &q2; 
      
    return 0; 
}
Responses