C语言之const

什么事const?const在C语言中平时有什么作用?其实C语言刚开始是没有const,const是C标准后面才新增的一个术语,可修改左词(modifiable lvalue),那么左词是什么理解的呢?举个例子吧!

int a;
a = 10;
printf("%d",a);
return 0;

如果是如上代码,运行则没有问题,a就是一个就简单的左词。

介绍完左词,还是回到const上面的问题,const是限定一个变量不允许被改变,产生静态作用。使用const在一定程度上可以提高程序的安全性和可靠性。另外,在观看别人代码的时候,清晰理解const所起的作用,对理解对方的程序也有一定帮助。如下是const的代码案例。

代码一:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(void) {
	int a = 1,b = 2;
	const int c = 3;
	int d = a + b;
	
	
	printf("%d.",d);
	
	return 0;
}

运行结果:

如上代码,是没有吧c加进去。

代码二:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(void) {
	int a = 1,b = 2;
	const int c = 3;
	int d = (a + b) * c;
		
	printf("%d.",c);
	
	return 0;
}

 运行结果:

const的用法如上所述。

发布了122 篇原创文章 · 获赞 36 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qqj3066574300/article/details/104326857