-------------------------------------资源来源于网络,仅供自学使用,如有侵权,联系我必删.
第一:
1.const 修饰变量
在C 语言中const 修饰的变量是只读的 , 其本质还是变量
const 修饰的变量会在内存占用空间
本质上const 只对编译器有用 ,在运行时无用
通过取地址符,改变地址里面的值
#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 ;
}
2.const 修饰数组
在C 语言中const 修饰的数组是只读的
const 修饰的数组空间不可被改变
3.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 出现在* 号右边时指针本身为常量
4.const 修饰函数参数和返回值
const 修饰函数参数表示在函数体内不希望改变参数的值
const 修饰函数返回值表示返回值不可改变 , 多用于返回指针的情形
第二:
volatile 可理解为“ 编译器警告指示字”
volatile 用于告诉编译器必须每次去内存中取变量值
volatile 主要修饰可能被多个线程访问的变量
volatile 也可以修饰可能被未知因数更改的变量
#include <stdio.h>
#include <malloc.h>
const int* func()
{
static int count = 0;
count++;
return &count;
}
int main()
{
volatile int i =0 ;
int* p = func();
printf("%d\n",*p);
return 0 ;
}