前言
提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。
提示:以下是本篇文章正文内容,下面案例可供参考
一、const修饰的只读变量
1.const修饰的变量,不可以直接被修改。
#include #include
int main()
{
const int i = 10;
int const i =10;//这两个等价的
i = 20; //报错,代表变量i不可以直接被修改
system("pause");
return 0;
}
2.const修饰的变量真的不能被修改吗?
#include <stdio.h>
#include <windows.h>
int main()
{
const int i = 10;
int *p = (int*)&i;
printf("before: %d\n", i);
*p = 20;
printf("after: %d\n", i);
system("pause");
return 0;
}通过指针进行修改,编译通过且能运行
结论:const修饰的变量并非是真的不可被修改的变量
那const修饰变量,意义何在?
1. 让编译器进行直接修改式检查
2. 告诉其他程序员(正在改你代码或者阅读你代码的)这个变量后面不要改哦。也属于一种“自描述”含义
3.const修饰的变量,可以作为数组定义的一部分吗?
#include
#include
int main()
{
const int n = 100;
int arr[n];
system("pause");
return 0;
}
//在vs2022(标准C)下直接报错了,因为中括号中必须是常量、宏定义或者不屑,但是在gcc(GNU扩展)下,可以
//但我们一切向标准看齐,不可以。
4.const只能在定义的时候直接初始化,不能二次赋值。
const int a;
a=10;
//编译不通过
二、const修饰数组
1.const修饰数组的两种方法:
1.const int a[]={0};
2.int const a[]={0};
2.不可进行如下操作
三、const修饰指针
1.修饰指针的四种情况:
说明(a=10;int * p=&a; p的内容为a的地址,p指向的变量为10)
1.const int * p; // p的内容可变,p指向的变量不可直接被修改
2.int const * p; // p的内容可变,p指向的变量不可直接被修改
3.int * const p; // p的内容不可直接被修改,p指向的变量可变
4.const int * const p; // 指针p和p指向的变量都不可直接被修改
四、const修饰函数参数
void show(const int* _p)
{
printf("hello world");
}
int main()
{
int a = 10;
int* p = &a;
show(p);
return 0;
}
加上const是预防性编程,防止写代码时出错,使得代码更加健壮
五、const修饰函数返回值
#include <stdio.h>
#include <windows.h>
//告诉编译器,告诉函数调用者,不要试图通过指针修改返回值指向的内容
const int* test()
{
static int g_var = 100;
return &g_var;
}
int main()
{
int *p = test(); //有告警
//const int *p = test(); //需要用const int*类型接受
*p = 200; //这样,【在语法/语义上】,限制了,不能直接修改函数的返回值
printf("%d\n", *p);
system("pause");
return 0;
}
//一般内置类型返回,加const无意义。