C语言中似是而非的const

探究C语言中似是而非的const

绝大多数学习过C语言的人都知道被const修饰的变量是只读的,但今天我要告诉大家其本质是变量,其所修饰的变量又可分为全局(global)变量和局部(local)变量,而局部变量又可分为一般局部变量和static修饰的局部变量,编译器不允许被const修饰的变量出现在赋值符号的左端,也就是不可作为左值。错误示例代码如下:

#include <stdio.h>

int main()
{	
	const int good = 80;
	
	good = 70; // error
	
	return 0;
}

那那那真的就没辙了吗?The answer is no,我们偷偷地利用一下指针,show time,怪盗基德登场。

#include <stdio.h>

int main()
{
	const int failed = 50;
	
	int* p = (int* )&failed;
	
	printf("the initial (failed) = %d\n",failed);// 打印最初的failed变量
	
	*p = 40;		//把40赋值给failed变量
	
	printf("now (failed) it's = %d\n",failed);
	
	return 0;	
}

outcome如下:
在这里插入图片描述
是不是发现不变的变量被改变了,指针可真great,but,物极必反,在现代C语言编译器中,const将具有全局生命周期的变量存储于只读存储区,换句话说,即将全局变量和static修饰的局部变量存储与只读存储区,如果试图在程序中去修改const修饰的全局变量和static局部变量,将会导致程序直接崩溃。
我们再来看代码:

#include <stdio.h>

int const good = 100;	//const int 与int const 等价

int main()
{
	int const failed = 50;
	
	int* p = (int* )&good;
	*p = 90;		//此处将导致程序崩溃
	printf("now good = %d\n",good);
	
	p = (int* )&failed;
	*p = 50;		//此处也会导致程序崩溃
	printf("now failed = %d\n",failed);
	
	return 0;
}

有const修饰的函数参数表示在函数体内该参数的值不希望被改变,cosnt修饰函数返回值时,说明返回值不可改变,多用于返回指针的情形,一旦尝试在程序中改变其内容将导致程序崩溃,furthermore,C语言中的字符串字面量存储于只读存储区中,在程序中需要使用const char* 指针。contine coding:

#include <stdio.h>

const char* func(const int i)
{
	i = 110;	//error,const修饰的变量不可做为左值使用
	return "hello world";
}
int main()
{
	const char*p = func();
	printf("%s\n",p);

	p[6] = '+';	//error,不允许修改const修饰的返回值,否则程序将崩溃
	printf("%s\n",p)
}

Yes,of course,上述描述只是const用法的冰山一角,日后将会继续写关于const关键字的用法。

猜你喜欢

转载自blog.csdn.net/Dream136/article/details/103876256