前言
狄泰软件唐老师的个人学习笔记
1、void
void 一般我们用来修饰函数返回值和函数参数
- 函数没有返回值,将其声明为void
- 函数没有参数,声明参数为void
实验:函数的返回值和参数不加void,不是说明无,而是什么都可以
#include <stdio.h>
f()
{
}
int main()
{
int i = f(1,2,3);
return 0;
}
- void是一种类型,但是不能修饰变量
1.1、void指针的意义
- C语言规定只有相同类型的指针才可以相互赋值
- void* 指针作为左值用于接收任意类型的指针
- void* 指针作为右值 使用时需要进行强制类型转换
实验:void* 使用说明
#include <stdio.h>
#include <malloc.h>
int main()
{
int* PI = (int*)malloc(sizeof(int));
char* PC = (char*)malloc(sizeof(char));
void* p = NULL;
int* pin = NULL;
char* pcn = NULL;
p = PI; ///void作为左值,可以接收任意类型
// pin = p; error,类型不一致,
p = PC;
// pcn = p;
return 0;
}
2、const
const:只读变量
- const是修饰只读变量,本质还是变量(不是常量),不能作为左值使用
- const修饰的局部变量在栈上分配空间,修饰的全局变量,在全局数据区(不一定)分配空间
- 现代C语言,将const修饰的全局变量存储于只读存储区,修改变量将导致程序崩溃
- 标准c语言,将const修饰的全局变量存储于全局数据区,可以正常改变
- 纯纯看编译器 - const只在编译器有用,在运行期无用
实验:const修饰的是只读变量,不是常量
#include <stdio.h>
int main()
{
const int cc = 3;
int* p = (int*)(&cc);
printf("%d\n", cc);
*p = 4;
printf("%d\n", cc);
return 0;
}
可以通过指针操作,更改变量值,说明还是变量
将 cc 改为全局变量,有的编译器会崩溃(现代C语言),用指针也不行,他将变量存于只读存储区,有的编译器正常编译(标准C语言),变量存于全局数据区
实验
#include <stdio.h>
int const g_array[5] = {0};
void modify(int* p, int v)
{
*p = v;
}
int main()
{
int const i = 0; //int const 和 const int一个东西
const static int j = 0; //静态只读变量 ,static修饰的局部变量具有全局生命周期 ,不能更改
int const array[5] = {0};
modify((int*)&i, 2);
// modify((int*)&j, 2);
modify((int*)&array[0], 2);
// modify((int*)&g_array[0], 2);
printf("%d\n", i); //2,局部变量,可以修改
// printf("%d\n", j); //error
printf("%d\n", array[0]); //2
// printf("%d\n", g_array[0]); //error
return 0;
}
实验:const修饰函数返回值,表明返回值不能更改,一般用于返回值指针
#include <stdio.h>
const char* f(const int i)
{
return "liang"; //字符串字面量存储于只读存储区
}
int main()
{
const char* pc = f(0);
printf("%s\n", pc);
pc[4] = 'a'; //error,const char* 不能改
printf("%s\n", pc);
return 0;
}
3、volatile
这个目前理解不深刻,以后填坑