用来修饰函数中的形参,防止误操作
测试源码
#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,所以编译器会检测误操作,该项的内容是只读的,不允许修改。
#include <stdio.h>
int main(int argc, const char *argv[])
{
int a = 1;
int b = 2;
/*1.指向常量的指针变量*/
const int* p1 = &a;
int const* p3 = &a;
/*2.指向变量的常指针*/
int *const p2 = &a;
*p2 = b;
//p2 = &b;
/*3.指向常量的常指针*/
const int* const p4 =&a;
// *p4 = b;
// p4 = &b;
return 0;
}