用来修饰函数中的形参,防止误操作
测试源码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Person
{
char name[64];
int age;
int Id;
double score;
};
//const使用场景,修饰函数中的形参,防止误操作
void printPerson( const struct Person *p )
{
//p->age = 100; 加入const之后 编译器会检测误操作
//printf("姓名: %s 年龄: %d 学号: %d 分数: %f\n", p.name, p.age, p.Id, p.score);
printf("姓名: %s 年龄: %d 学号: %d 分数: %f\n", p->name, p->age, p->Id, p->score);
}
void test01()
{
struct Person p1 = { "test", 28, 1, 100 };
printPerson(&p1);
printf("%d\n", p1.age);
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
测试结果
关键代码分析
p->age = 100;
因为函数参数中加入const,所以编译器会检测误操作,该项的内容是只读的,不允许修改。