C语言和C++中的const用法和异同

C语言中const:

在C语言中const修饰的变量是只读的,其本质还是变量
const修饰的变量会在内存占用空间
本质上const只对编译器有用,在运行时无用
—原来const不是真的常量—

#include <stdio.h>
#include <malloc.h>

int main()
{
	const int cc = 1;	
	printf("%d\n", cc);

	cc = 3; //error
	printf("%d\n",cc);

	return 0;
}

运行结果:

在这里插入图片描述

代码:

#include <stdio.h>
#include <malloc.h>

int main()
{
	const int cc = 1;
	int* p = (int*)&cc;

	printf("%d\n", cc);	

	*p = 3;
	printf("%d\n",cc);

	return 0;
}

运行结果:

在这里插入图片描述

const修饰数组:

在C语言中const修饰的数组是只读的(类似const int cc,也会分配内存空间)

#include <stdio.h>
#include <malloc.h>

int main()
{
	const int array[5] = {1,2,3,4,5};

	array[0] = 8;

	int i;
	for(i=0; i<5; i++)
	{
		printf("%d\n",array[i]);
	}	
	
	return 0;
}

运行结果:

在这里插入图片描述

const修饰指针:

const int* p; //p可变,p指向的内容不可变

int const* p; //p可变,p指向的内容不可变

int* const p; //p不可变,p指向的内容可变

const int* const p; //p和p指向的内容都不可变

口诀:

当const出现在 * 号左边时指针指向的数据为常量
当const出现在 * 后右边时指针本身为常量

const修饰函数参数和返回值:

const修饰函数参数表示在函数体内不希望改变参数的值

const修饰函数返回值表示返回值不可改变,多用于返回指针的情形

#include <stdio.h>
#include <malloc.h>

const int* func()
{
	static int count;
	count++;
	return &count;
}

int main()
{
	int i;
    
	const int* p = func();
	printf("%d\n",*p);
	
	return 0;
}

运行结果:

在这里插入图片描述

C++中的const

#include <stdio.h>
#include <malloc.h>

int main()
{
	const int c = 0;
	int* p = (int*)&c;

	*p = 5;
	
	printf("c = %d\n",c);
	
	return 0;
}

运行结果:

在这里插入图片描述
C++编译器对const常量的处理

当碰见常量声明时在符号表中放入常量

编译过程中若发现使用常量则直接以符号表中的值替换

编译过程中若发现对const使用了extern或者&操作符,则给对应的常量分配存储空间

注意:C++编译器虽然可能为const常量分配空间,但不会使用其存储空间中的值。

图示:

在这里插入图片描述

C++中的const是真正意义上的常量:

test.c

#include <stdio.h>
#include <malloc.h>

int main()
{
	const int a =1;
	const int b = 2;

	int array[a+b] = {0}; //在C语言中const int a是只读变量,不是真正意义上的常量。
	int i = 0;

	for(i = 0; i<a+b; i++)
	{
		printf("array[%d] = %d\n",i,array[i]);
	}	
	
	return 0;
}

运行结果:

在这里插入图片描述
test.cpp

#include <stdio.h>
#include <malloc.h>

int main()
{
	const int a =1;
	const int b = 2;

	int array[a+b] = {0}; //相当于array[1+2]  在C++中const int a是真正意义上的常量。
	int i = 0;

	for(i = 0; i<a+b; i++)
	{
		printf("array[%d] = %d\n",i,array[i]);
	}	
	
	return 0;
}

运行结果:

在这里插入图片描述

C++中的const和宏定义的区别:

经过上面的分析,感觉好像c++中的const和宏定义很像,他们两个有什么区别那?

const常量是由编译器处理的,提供类型检查和作用域检查

宏定义由预处理器处理,单纯的文本替换

宏定义代码:

#include <stdio.h>
#include <malloc.h>

void f()
{
	#define a 3

//	const int b = 4;
}

void g()
{
	printf("a = %d\n",a);

//	printf("b = %d\n",b);
}

int main()
{
	f();
	g();
	
	return 0;
}

运行结果:

在这里插入图片描述
C++中的const常量代码:

#include <stdio.h>
#include <malloc.h>

void f()
{
//	#define a 3

	const int b = 4;
}

void g()
{
//	printf("a = %d\n",a);

	printf("b = %d\n",b);
}

int main()
{
	f();
	g();
	
	return 0;
}

运行结果:

在这里插入图片描述

未完待续

涉及类和引用等c++的特性所用到const以后再添加,未完待续…

猜你喜欢

转载自blog.csdn.net/QQ1402369668/article/details/88030094