3.02定义常量之const

【注:本程序验证是使用vs2013版】

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)

//5、const跟结构体配合使用
typedef struct MyStruct{
    int a;
    int b;
}MyStruct;

void fun(MyStruct  *p){
    //指针和指向内存都可以变
    p = NULL;//ok
    p->a = 10;//ok
}

void fun1(MyStruct const *p){
    p = NULL;//ok            //指针可以改变
    //p->a = 10;//err        //指针指向不可以改变
    
}

void fun2(MyStruct * const p){
    //p = NULL;//ok            //指针不可以改变
    p->a = 10;//ok            //指向的内存可以改变
}

void fun3(MyStruct const * const  p){
    //只可以读取
    MyStruct tmp;
    tmp.a = p->a;
}

int main(void){
    //const 修饰一个变量为只读
    const int a = 10;
    //a = 100; //err

    /*
    2、跟指针变量配合使用,
    主要考察:指针变量和指针指向的内存,2个不同的概念
    从左往右看,跳过类型,看修饰哪个字符,
    如果是*,说明说明指针的指向内容不能变
    如果是指针变量,说明指针的指向不能改变(指针的值不能改变)
    */
    char buf[] = "asdwqfqwerqw";
    const char *p = buf;//不可以改变指向的buf的内容,可以修改指针的指向
    //等价于上边 char const *p = buf
    //p[1] = '2';//err
    p = "asdwqdq";//ok

    char * const p1 = buf;
    p1[1] = '3'; //ok
    //p1 = "asdwqdq";//err

    const char * const p2 = buf;//p3为只读,指向不能改变,指向的内存也不可以改变


    /*
    3、如果引用另外.c中的const变量(不常用,了解)
    extern const int x;//不能再赋值,只能声明
    const修饰的变量,在定义的时候必须初始化
    */


    /*
    4、可以通过指针修改const修饰的变量的值,
    const 修饰b,只是要求不能直接操作b。
    这里c语言不太严谨。
    */
    const int b = 10;
    int *q = &b;
    *q = 11;
    printf("b=%d", b);

    printf("\n");
    system("pause");
    return 0;
}

 

posted @ 2019-07-01 06:42  大黄蜂_001  阅读(274)  评论(0编辑  收藏  举报