解析C与C++中的关键字const
在C与C++语言中都存在关键字const,很多人都对此关键字存在一个错误的认识,认为在C语言中关键字const是使变量作为一个常量,即将变量常量化,就像宏定义一样。而在C语言中的关键字const所起的作用并不是使变量常量话,而是限制变量,使变量除了被赋初值外,无法被重新赋值。
而在C++中关键字const不仅使该变量无法修改,也是使变量常量化,即将变量赋初值后可以当作常量使用,相当于进行了宏定义。
在编译器中输入以下代码,你会有更直观的体会。
在C语言编译器中:
/* const限制的变量的值无法修改*/
#include <stdio.h>
int main(void)
{
const int a=1;
int const b=1;
a=1;
b=1;
system("pause");
return 0;
}
当你将这段代码编译时,编译器会报错:在mian函数中无法修改const限制的对象。
注:在C语言中,关键字const被放在标识符之前或之后是一样的效果。
/* const限制的变量无法修改*/
#include <stdio.h>
int main(void)
{
const int a=1;
switch(1)
{
case a:prinf("variable a can be used as constant");break;
default :printf("variable a cannot be used as constant");
}
system("pause");
return 0;
}
当你编译这段代码是,编译器会报错:在main函数中要求使用常量。
关键字const对指针的限制:
/*cosnt在*前,指针指向对象的值无法修改*/
#include <stdio.h>
int main(void)
{
int a=1,b=2;
const int * p1=&a;
int const * p2=&b;
*p1=1;
*p2=1;
system("pause");
return 0;
}
const在星号前对对指针变量进行限制时是对指针变量所指向的对象进行限制,针对上列代码就是对a,b进行限制,使a,b不能被重新赋值,因此编译时会报错:在mian函数中无法修改const限制的对象。但两个指针变量的值是可以修改的。编译下列代码:
/* cosnt在*前,指针变量的值可以修改*/
#include <stdio.h>
int main(void)
{
int a=1,b=2;
const int * p1=&a;
int const * p2=&b;
printf ("a=%d\nb=%d\n",*p1,*p2);
p1=&b;
if(p1==p2)
printf("the address of p1 is equal to the address of p2\n");
system("pause");
re
相关文档:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
main()
{
FILE *fp;
if ( (fp = fopen( "c:\\a.txt", "r" )) == NULL ) printf("ERROR!\n");
int tmp[MAXSIZE];
int i;
for ( i=0; i<MAXSIZE; i++ )
{
tmp[i] = 0; ......
<!--
/* Font Definitions */
@font-face
{font-family:宋体;
panose-1:2 1 6 0 3 1 1 1 1 1;
mso-font-alt:SimSun;
mso-font-charset:134;
mso-generic-font-family:auto;
mso-font-pitch:variable;
mso-font-signature:3 135135232 16 0 262145 0;}
@font-face
{font-family:"\@宋体" ......
虽然学习了好多年,但需要细究某些基础知识的时候还是发现自己忘了, 从别人的文章扒过来,以备复习
参考: http://blog.csdn.net/masefee/archive/2009/12/28/5090820.aspx
============================================================
之前的定位可能主要为了研究底层及一些较复杂的问题上,而忽略了一些初学的朋友。导 ......