const用法

#include <stdlib.h>
#include <stdio.h>

void show_array(const double ar[], int n);
void mult_array_one(double ar[], int n);
void mult_array_two(const double ar[], int n);

int main(int argc, char const *argv[])
{
    /*
    1、指针常量和常指针
    */
    double rate[5] = {10.11,20.12,30.44,50.32,70.32};
    //常量指针,常指针,即指向的数据是一个常量,值不能变
    const double *p1 = rate;
    //指针常量,即指针是一个常量,地址不能变
    double * const p2 = rate;

    printf("原首元素:%f\n",p1[0]);
    //p1[0] = 33;//错误
    p2[0] = 90;
    printf("现首元素:%f\n",rate[0]);

    printf("原地址:%p\n",rate);
    //p2 = &rate[2];//错误
    p1 = &rate[2];
    printf("现地址:%p\n",p1);

    /*
    2、非const数据的地址只能赋值给普通指针,不能赋值const指针,否则就能通过指针改变const数组的数据
    */
    const double lock[5] = {2.1,3.4,23.11,23.55,89.33};
    const double *t1 = lock;
    //double *t2 = lock;//错误

    /*
    3、const修饰形参,保护传入形参的值不被改变,即只读
    */
    double sea[5] = {2.1,3.4,23.11,23.55,89.33};
    
    mult_array_two(sea,5);
    show_array(sea,5);

    mult_array_one(sea,5);
    show_array(sea,5);

    return 0;
}

void test_const()
{
    const int y = 10;
    const int *p = &y;
    int *q;
    /*
    4、const指针赋值给非const指针,C发出警告,C++会报错
    */
    q = p;   
    *q = 20; //通过非const指针修改const值,该行为未定义
    printf("%d ",*q);
}

void show_array(const double ar[], int n)
{
    int i;
    for(int i=0; i<n; i++){
        printf("%8.3f ", ar[i]);
    }
    putchar('\n');
}

void mult_array_one(double ar[], int n)
{
    double sum = 0;
    for(int i=0; i<n; i++){
        sum += ar[i]++;//ar[]数组中的值被改变
    }
    printf("%f\n",sum);
}

void mult_array_two(const double ar[], int n)
{
    double sum = 0;
    for(int i=0; i<n; i++){
        //sum += ar[i]++;//报错:ar[] is read-only
    }
    printf("%f\n",sum);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值