const int joy = 101;
建立了一个变量joy,它的值固定为101.
volatile unsigned int incoming;
表明incoming 在程序中的两次出现之间它的值可能会改变
const int *ptr = &joy;
表明指针ptr的值 不能用来改变joy的值,但是它可以指向另外的一个位置
void simple(const char *s);
在形式参数s 被初始化为在函数调用中传递给simple() 的任何值之后 simple() 不能改变s 指向值
int *const ptr = &joy;
指针ptr 只能指向joy ,可以使用ptr来改变 joy的值
void supple(int *const pi); 相当于 void supple(int pi[const]);
函数不会改变参量 pi的值 即 pi的所指向
#include<stdio.h>
void print(int a)
{
printf("%d\n",a);
}
/*
//const.c:12: error: assignment of read-only location ‘*s’
//const.c:13: error: assignment of read-only location ‘*s2’
void const_test(const int *s, const int *s2)
{
int t;
t = *s;
*s = *s2;
*s2 = t;
}
*/
/*
int *const_test(const int *s, const int *s2)
{
int t = 10;
*s = &t
printf("%d\n", *s);
return s;
}
*/
void const_test(int *const pi)
{
printf("pi[const] = %d\n", *pi);
*pi = 5;
int a = 10;
// pi = &a; const.c:37: error: assignment of read-only location ‘pi’
}
int main(int argc, char **argv)
{
const int joy = 101;
printf("const int joy = %d\n", joy);
//joy = 100; //const.c:6: error: assignment of read-only variable ‘joy’
volatile unsigned int incoming;
incoming = 10;
print(incoming);
print(incoming);
const int *ptr = &joy;
printf("*ptr = %d\n", *ptr);
//*ptr = 100; // const.c:18: error: assignment of read-only location ‘*ptr’
int s = 1;
int s2 = 2;
// const_test(&s, &s2); //
printf("s = %d\n", s);
printf("s2 = %d\n", s2);
int *const ptr_2 = &joy;
printf("*ptr_2 = %d\n", *ptr_2);
*ptr_2 = 100;
printf("*ptr_2 = %d\n", *ptr_2);
//ptr_2 = &s; //const.c:58: error: assignment of read-only variable ‘ptr_2’
//printf("*ptr_2 = %d\n", *ptr_2);
int array[3] = { 0, 1, 2};
const_test(&array[1]);
printf("array[1] = %d\n", array[1]);
return 0;
}