const volatile 关键字

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值