1.const修饰变量
正常不能改变:
#include <stdio.h>
int main()
{
const int a = 1;
a = 2; //报错
printf("%d\n", a);
return 0;
}
用指针后可以改变:
#include <stdio.h>
int main()
{
const int a = 1;
int* p = &a;
*a = 2;
printf("%d\n", a);
return 0;
}
2.const修饰数组
正常不能改变:
#include <stdio.h>
int main()
{
const int A[5] = {1, 2, 3, 4, 5};
int i = 0;
for(i=0; i<5; i++)
{
A[i] = 5 - i; //报错
}
for (i=0; i<5; i++)
printf("%d\n", A[i]);
return 0;
}
用指针后可以改变:
#include <stdio.h>
int main()
{
const int A[5] = {1, 2, 3, 4, 5};
int* p = (int*)A;
int i = 0;
for(i=0; i<5; i++)
{
p[i] = 5 - i;
}
for (i=0; i<5; i++)
printf("%d\n", A[i]);
return 0;
}
3.const修饰指针
正常不能改变:
#include <stdio.h>
int main()
{
int* const pH = "Hello";
int* const pW = "World";
pH = pW; //报错.
printf(pH);
return 0;
}
用指针后可以改变:
#include <stdio.h>
int main()
{
int* const pH = "Hello";
int* const pW = "World";
int** p = &pH;
*p = pW;
printf(pH); //打印出来是“World”.
return 0;
}
4.const修饰函数参数和返回值
正常不能改变:
#include <stdio.h>
#include <malloc.h>
const int* func()
{
static int count = 0;
count++;
return &count;
}
int main()
{
int i = 0;
const int* p = func();
*p = 5; //报错
printf("%d\n", *p);
return 0;
}
用**后可以改变:
#include <stdio.h>
#include <malloc.h>
const int* func()
{
static int count = 0;
count++;
return &count;
}
int main()
{
int i = 0;
int* p = func(); //会有警告,但能过去
*p = 5;
printf("%d\n", *p); //打印5
return 0;
}