常量指针 vs 指向常量的指针 [英] Constant pointer vs Pointer to constant

查看:34
本文介绍了常量指针 vs 指向常量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道

const int* ptr;

int * const ptr; 

以及它是如何工作的.

我很难理解或记住这一点.请帮忙.

It is pretty difficult for me to understand or keep remember this. Please help.

推荐答案

const int* ptr; 

声明 ptr 一个指向 const int 类型的指针.可以修改ptr本身,但不能修改ptr指向的对象.

declares ptr a pointer to const int type. You can modify ptr itself but the object pointed to by ptr shall not be modified.

const int a = 10;
const int* ptr = &a;  
*ptr = 5; // wrong
ptr++;    // right  

虽然

int * const ptr;  

声明 ptr 一个 const 指向 int 类型的指针.ptr是不允许修改的,但是ptr指向的对象是可以修改的.

declares ptr a const pointer to int type. You are not allowed to modify ptr but the object pointed to by ptr can be modified.

int a = 10;
int *const ptr = &a;  
*ptr = 5; // right
ptr++;    // wrong

通常我更喜欢这样的声明,它易于阅读和理解(从右到左阅读):

Generally I would prefer the declaration like this which make it easy to read and understand (read from right to left):

int const  *ptr; // ptr is a pointer to constant int 
int *const ptr;  // ptr is a constant pointer to int

这篇关于常量指针 vs 指向常量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆