C语言中的const只是一个冒牌货(const的作用,论述const在C语言中为何冒牌)

const的作用,论述const在C语言中为何冒牌

一.const的作用
1.const修饰的变量为只读,即变量不可以被修改,相当于一个常量,例如:

#include <stdio.h>
int main()
{
	const int b = 10;//const修饰的变量不可以被修改
	b = 100;//err
	return 0;
}

2.const修饰指针时,两种不同的用法分为 指针变量和指针指向的内存,两个不同的概念,例如:

#include <stdio.h>
int main()
{
	char buf[] = "akjefbefbijewf";
	//从左往右看,跳过类型,看const修饰哪个字符
	//如果修饰的时*,说明指针指向的内存不能发生改变,即指针所指向的内存只能读,不可以写
	//如果修饰的是指针变量p;说明指针的指向不能发生改变,即指针的值不可以修改
	const char *p = buf;//const修饰*,所以指针所指向的能容不能改变即如果//p[1]='1';//err
	char const *p2 = buf;
	const char * const p3 = buf;//两个const修饰即修饰*又修饰指针变量,
	                                           //所以,p3只能读,指向的内存也不能 改变  
	return 0;
}

3.const修饰指针在结构体中的综合使用,代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
typedef struct  SKT
{
	int a;
	int b;
}SKT;
void fun(SKT *p)
{
	//没有const修饰,指针可以变,指针所指向的内存也可以改变;
	//p->a = 10;//ok;
	//p = NULL;//ok
}
void fun1(SKT const *p)
{
	//p = NULL;//ok
	//p->=10;//err
}
void fun2(SKT *const p)
{
	//p = NULL;//err
	//p->a = 10;//ok
}
void fun3(SKT const *const p)
{
	//const修饰两个都修饰,只能读取
}
int main()
{
	system("pause");
	return 0;
}

二.C语言中的const是一个冒牌货
为什么这么说呢,因为在C语言中,const修饰的变量,可以通过指针进行间接赋值,例如:

#include <stdio.h>
int main()
{
	const int a = 10;
	//a = 20;//err    const修饰这样的赋值会直接报错
	int *p = &a;
	*p = 20;
	printf("a=%d,*p=%d\n", a, *p);
	return 0;
}

通过指针的间接赋值,const已经发挥不到他的作用。

猜你喜欢

转载自blog.csdn.net/a_hang_szz/article/details/88530487