文章目录
一、assert()函数
引用头文件<assert.h>
是用来断言的函数:当程序执行到断言的位置时,对应的断言应该为真。若断言为假,将一条消息写入标准错误设备并被调用,从而终止程序执行
1.原型声明
#include <assert.h>
void assert(int expression);
2.调用
assert(条件表达式);
3.作用
计算表达式的值,如果值为真(即非0值),程序继续往后走,函数什么也不做;如果值为假(即为0),将会终止程序执行,报错,并给出函数的行数
相当于一个if()语句
4.用法
一般将assert对一个函数的参数进行空指针检查,判断指针是否为空
当出现空指针时,程序会报错退出,并给出错误的位置
/* assert 对函数的参数进行空指针检查,判断指针是否为空 */
#include <stdio.h>
#include <assert.h>
void print_number(int* p)
{
assert(p != NULL);
printf("%d\n", *p);
}
int main()
{
int num = 10;
int* p1 = NULL;
int* p2 = NULL;
p1 = #
print_number(p1);
print_number(p2);
return 0;
}
5.例子
例: 创建一个函数,可以交换两个整型的值,用assert()函数对参数进行空指针检查
下面是在使用assert()函数时,条件表达式为真和为假的情况(不报错和报错)
#include <stdio.h>
#include <assert.h>
void exchange(int* x, int* y)
{
assert(x != NULL);
assert(y != NULL);
//可以直接写成 assert(y)
int z = 0;
z = *x;
*x = *y;
*y = z;
}
int main()
{
int num1 = 0, num2 = 0; int* p1 = NULL, * p2 = NULL;
num1 = 22;
num2 = 33;
p1 = &num1;
p2 = &num2;
//p2 = NULL;令p2指向NULL,导致报错
printf("交换前:a=%d b=%d\n", num1, num2);
exchange(p1, p2);
printf("交换后:a=%d b=%d\n", num1, num2);
return 0;
}
运行结果:先是不报错的,后面是指针 p2 指向 NUll 导致报错的
二、const类型限定符
1.在普通变量和数组声明中使用const
const用于修饰常变量
const int num=10; //使num成为一个只读值,本质是变量
const int a[5] = {1, 2, 3, 4, 5};
2.在指针和形参声明中使用const
对指针使用const来说,要区分是限定指针本身为const还是限定指针指向的值为const
(1)const修饰指针变量时
<1>int* const p;
如果const在 * 右边,修饰的是指针变量 p,表示指针变量不能被改变,但是指针指向的内容可以改变通过指针来改变的
<2>const int* p;
如果const在 * 左边,修饰的是 *p,表示指针指向的内容,是不能通过指针来改变的,但是指针变量本身可以修改(比如设置指针 p 指向其他变量)
int const* p;
同理
<3>const int* const p;
如果 * 两边各有一个 const,指针p 既不能指向别处,他所指向的值也不能改变
(2)const常用于声明为函数形参的指针
例如要调用一个函数显示一个数组的内容。把数组名作为实参传递给该函数,要保证数据不被更改,可以用 const 声明函数形参的指针
void display(const int* parr, int limit);
//或者
void display(const int arr[], int limit);
在函数原型和函数头,形参声明
const int arr[]
与const int* arr
相同