Understanding of const int and int const, const int * and int const *, int * const in C language

Foreword:

1. General Definition

const is a keyword in the C language, the value of the variable or object of the modified data type cannot be changed.

2. Purpose of launch

The initial purpose is to replace precompiled instructions

3. The main role

1) Define const constant, with immutability

2) Facilitate type checking

3) Prevent accidental modification

4) Save space and provide efficiency

Examples:

1.const int和int const

#include "stdio.h"

int main(void)
{
    const int a = 10;
    //int const a = 10;   //同上句代码作用等同
    //a = 20;             //取消注释此句会报错,因为a的值不可变
    printf("%d\n",a);
    return 0;
}

2.const int *和int const *

#include "stdio.h"

int main(void)
{
    int a = 10;
    int b = 20;
    const int *c = &a;    //const修饰的是int,也即是*c的值不可变,但c指针可变
    //int const *d = &a;  //同上句代码作用等同
    //*c = 20;            //取消注释此句会报错,因为*c的内容不可变
    c = &b;               //可以修改c,指向新的地址
    printf("%d\n",*c);
    return 0;
}

3.int *const 

#include "stdio.h"

int main(void)
{
    int a = 10;
    int b = 20;
    int *const c = &a;    //const修饰的是指针c,所以c是常量指针,但存储的地址所指向的内容可变
    //c = &b;             //取消注释此句会报错,因为c是常量指针
    *c = 30;
    printf("%d\n", *c);
    return 0;
}

 

Published 81 original articles · 21 praises · 30,000+ views

Guess you like

Origin blog.csdn.net/qq_33575901/article/details/98659122