解析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>
#include<conio.h>
#include<string.h>
#include<windows.h>
#include<malloc.h>
#include<math.h>
typedef struct worker
{
int num; //编号
char name[15]; //姓名
char zhicheng[15];& ......
曾经碰到过让你迷惑不解、类似于int * (* (*fp1) (int) ) [10];这样的变量声明吗?本文将由易到难,一步一步教会你如何理解这种复杂的C/C++声明。
我们将从每天都能碰到的较简单的声明入手,然后逐步加入const修饰符和typedef,还有函数指针,最后介绍一个能够让你准确地理解任何C/C++声明的“右左法则”。 ......
没想到 没想到 万万没想到
对C++八窍只通了7窍的我,竟然要开始搞c++了的说,真是好不刺激。
不敢相信,不敢相信。
类型是什么玩意?类怎么写?字符串怎么处理?怎么释放内存?
偶不知,不知,真的不知。。。。
哎 完都完了。
唉 不管怎么说都要去学的。。。一点辙都没有
#incl ......