码迷,mamicode.com
首页 > 编程语言 > 详细

c语言const关键字

时间:2014-10-20 23:25:57      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   使用   strong   sp   

作者:沉默羔羊


c语言const关键字:

    --  特点。

        使用该关键修饰的变量不能被改变

     --指针常量。

       demo:  

        const char *p或者是 char const * p

     --常量指针。

      demo:

       char * const p

     --常量指针和指针常量。

      1.常量指针指的是如 char * const p, p是一个常量,p不能改变指向。

      2.指针常量指的是如char const *p,   p指向一个字符常量,p可以改变指向。但是不能改变*p.

    --对于常量指针和指针常量的记忆方法如下。

        The C++ Programming Language里面给出过一个助记的方法:

把一个声明从右向左读。

char * const cp; ( * 读成 pointer to ) cp is a const pointer to char

const char * p; p is a pointer to const char;

/*************************************************************************
    > File Name: const1.c
    > Author: 沉默羔羊
    > Mail: zshh0604@163.com 
    > Created Time: 2014年10月20日 星期一 19时29分01秒
 ************************************************************************/

#include<stdio.h>
#include<string.h>
#define CONST_POINTER
#define POINTER_CONST
int test(void)
{
/***
 * const:关键字,
 *     使用const修改的变量,初始化之后不能步修改。
 *
 * 该关键值使用之后比较容易产生疑问的表达式:
 *		一:指针常量
 *			const char *p;
 *			或者是
 *			char const *p;
 *		二:常量指针
 *			char * const p;
 *		三:常量指针也是指针常量的表达式。
 *			const char * const *p;
 *
 * The C++ Programming Language里面给出过一个助记的方法:
 *		把一个声明从右向左读。
 *  	char * const cp; ( * 读成 pointer to ) cp is a const pointer to char
 *		const char * p; p is a pointer to const char;
 */	
	int a = 10;
	int b = 20;
	const int * p0;       //指针常量
    int const * p1;       //指针常量
	int * const p2 = &b;  //常量指针。
	const int * const p3 = &a;

#ifdef CONST_POINTER
	p0 = &a; 
	printf("p0 = %d\n",*p0); 
	p0 = &b;
	printf("p0 = %d\n",*p0);    
#if 0 
	*p0 = 10;      //p0是一个指向常量字符的指针。但p0不是常量。p0指向的是int类型的常量。
#endif
	p1 = &a;
	printf("p1 = %d\n",*p1);
	p1 = &b;
	printf("p1 = %d\n",*p1);
#if 0
	*p1 =10 ;     //更改指针指向的常量时变量会报错。
#endif 
#endif

#ifdef POINTER_CONST
#if 0
	p2 = &a;     //p2是个常量。修改p2的指向编译的时候会出错。
#endif
	*p2 = 30; 
	printf("p2 = %d\n",*p2);
#endif 

#if 0 
	*p3 = 10;  //编译错误。
	 p3 = &b;  //编译是错误。
#else
	printf("p3 = %d\n", *p3);
#endif
	return 0;
}
int main(void)
{
	test();
	return 0;
}


转载请标明出处

http://blog.csdn.net/shaohuazuo/article/details/40316987

c语言const关键字

标签:style   blog   http   color   io   ar   使用   strong   sp   

原文地址:http://blog.csdn.net/shaohuazuo/article/details/40316987

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!