c语言之const的用法
2018-04-12 19:58
218 查看
本篇博文简单的讲讲c语言的const的用法。
const:定义常变量,不能写,只读
a.数据类型对于const而言是透明的b.const用于封锁直接修饰的内容,将内容改变为只读
来段代码说明~~~
代码如下:
const:定义常变量,不能写,只读
a.数据类型对于const而言是透明的b.const用于封锁直接修饰的内容,将内容改变为只读
来段代码说明~~~
int main() { int a = 10;//读,写 int b = 20;//读,写 const int ca = 10;//读 int const cb = 20;//读 int *p = &a; p = &ca ;//错误//p是指针变量,&ca是const int*类型不能被改变 const int *cp1 = &ca;//正确//cp1是const int*类型的指针,&ca是const int*类型 cp1 = &b; cp1 = &ca;//正确 const int *cp2 = &ca;//正确 int *const cp3 = &a; int *const cp4 = &ca;//错误//cp1是int* const类型的指针,而&ca是const int*类型 const int *const cp5 = &a;//正确//cp5是const int * const类型的指针 const int *const cp6 = &ca;//正确 return 0; }c.权限只能同等传递或者缩小传递
代码如下:
int main() { int a = 10; a = 20;//左值,放在符号的左值,写权限 const int ca = 100;//只读 ca = 200;//错误,const类型不能被改变 ca = 100;//错误 const int cb;//错误//这里必须初始值设定,即赋初值 int const cb = 100;//正确//等价于ca int b = a; int *p = &a; p = &b; *p = 200; const int *cp1 = &a; cp1 = &b;//正确 *cp1 = 200;//错误//*cp1是const类型,不能被改变 int const *cp2 = &a;//等价于cp1 cp2 = &b; *cp2 = 200;//错误 int const *const ccp = &a; ccp = &b;//错误 *ccp = 100;//错误 }Ps: assert断言:断定表达式的结果一定为真 如果为真什么都不做,如果为假程序崩溃 只在debug版本有效
相关文章推荐
- C语言中const关键字的用法大全(包含与#define的区别)
- C语言const的用法(初级)
- C语言中const的用法
- C语言中关键字const、static、volatile的用法分析
- 详解C语言中const关键字的用法
- C语言中const关键字的用法
- 话说C语言const用法
- C语言const用法详解(一)(转载)
- C语言中const 的常见用法
- C语言中的const,free用法详解
- C语言const关键字的四种用法
- C语言const用法详解(二)(转载)
- C语言中const的用法
- C语言中const的用法
- 【C语言】程序断言和const的用法
- C语言中const的用法
- C语言中const关键字的用法
- C语言const用法详解(三)(转载)
- C语言中const的正确用法
- C语言中const的用法