非指针参数(也就是传值参数)不会被修改原始值, const 对它是没有意义的。
const 只用于指针。
1. 第一种用法: const 类型 *变量:
这种用法将限制修改指针指向的值。
|
#include <stdio.h>
int fun(const int *p) {
int main(void) |
2. 不过也有办法绕过这个限制:
|
#include <stdio.h>
int fun(const int *p) {
int main(void) |
2. 第二种用法: 类型 *const 变量:
这种用法将限制指针的指向; 下面的例子企图修改指针, 不会成功。
|
#include <stdio.h>
void swap(int *const p1, int *const p2) {
int main(void) |
3. 其实不使用 *const, 指针也不会被修改:
还是上面的例子, 去掉 const…… 函数也不会成功。
这是为什么呢? 因为指针的本身作为参数时也只是个副本(不过副本指向的值可是真的)。
|
#include <stdio.h>
void swap(int *p1, int *p2) {
int main(void) |
4. 但第二种方法不会现在修改指针指向的值:
这也最终可以完成这个 swap 函数; 就这个函数本身来讲, 完全可以不用 const.
|
#include <stdio.h>
void swap(int *const p1, int *const p2) {
int main(void) |
5. 甚至可以两种手段一起上:
|
#include <stdio.h>
int fun(int const *const p1, int const *const p2) {
int main(void) |

本文详细介绍了C语言中const限定符的多种用法,包括如何限制指针指向的值被修改,如何防止指针自身被改变指向,以及如何结合使用这两种方式。通过具体的代码示例展示了不同情况下const的应用技巧。
2630

被折叠的 条评论
为什么被折叠?



