关键字的秘密
专题一:关键字的秘密。包括以下章节:
- 基本数据类型分析
- auto,register,static分析
- if,switch,do,while,for分析
- goto,void,extern,sizeof分析
- const,volatile分析
- struct,union分析
- enum,typedef分析
const
- c语言中const修饰的变量是只读的
- const修饰的变量会在内存中占用空间
- const关键字只对编译器有用,运行时无用
- const修饰的变量可以通过指针修改,所以它不是严格意义上的常量
向coust修饰的变量赋值
5-1.c
#include <stdio.h>
int main()
{
const int i = 1;
printf("%d\n", i);
i = 0;
printf("%d\n", i);
return 0;
}
打印结果:
使用指针向coust修饰的变量赋值
5-1.c
#include <stdio.h>
int main()
{
const int i = 1;
printf("%d\n", i);
p = (int*)&i;
*p = 0;
printf("%d\n", i);
return 0;
}
打印结果:
const修饰数组
- c语言中const修饰的数组是只读的
- const修饰的数组空间是不可被改变(现代gcc编译器是可以改变的,不同编译器效果不同)
#include<stdio.h>
int main()
{
const int a[5] = {1,2,3,4,5};
int*p = (int*)a;
int i = 0;
for(i = 0; i < 5; i++)
{
printf("%d\n", a[i]);
}
for(i = 0; i < 5; i++)
{
p[i] = 5-i;
}
for(i = 0; i < 5; i++)
{
printf("%d\n", a[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在*右边,指针(p的值)不变
数据不可改变
#include<stdio.h>
int main()
{
int i = 0;
const int* p = &i;
//int const* p = &i;结果相同
*p = 3;
return 0;
}
打印结果:
指针不可改变
#include<stdio.h>
int main()
{
int i = 0;
int* const p = &i;
*p = 3;
p = NULL;
return 0;
}
打印结果
const修饰函数参数和返回值
- const修饰函数参数表示在函数体内不希望改变参数值
- const修饰返回值表示返回值不可改变,多用于返回指针类型
#include<stdio.h>
const int* func()
{
static int count = 0;
count++;
return &count;
}
int main()
{
int i = 0;
int *p = func();
//应该是const int* p= func()
printf("%d\n", *p);
return 0;
}
打印结果:
volatile
- volatile可以理解为“编译器警告指示字”
- volatile用于告诉编译器必须每次去内存中取值
- volatile多用于修饰可能被多线程访问的变量
- volatile也可以修饰可能被未知因素修改的变量
- volatile告诉编译器该变量不能被优化