const in C

void test_const_value()
{
    int n = 1;
    int m = 10;
    // ptr1 和 ptr2的声明时一个意思
    const int *ptr1 = &n;
    int const *ptr2 = &n;
    int *const ptr3 = &n;
    // ptr4 和 ptr5的声明时一个意思
    const int *const ptr4 = &n;
    const int const *ptr5 = &n;

    // 下面三个报的错都是一样的:表达式必须是可以修改的左值
    // *ptr1 = 100; 错误 不能修改指向的元素的值
    // *ptr2 = 100; 错误同上 不能修改 其实ptr1和ptr2是一样的意思
    // ptr3 = &m; 错误 指向不能变
    *ptr3 = 100; //正确 指向不能变 但是指向的地方的内容不能变
    // ptr4 = &m;
    // *ptr4 = m;
}

void test_const_array(const int a[],int num)
{
    // a[0] = 10; 错误 用const修饰的数组不可更改内容
    // 一般传递数组时 如果不希望数组被改变 就要使用const修饰 否则有被修改的风险
}

猜你喜欢

转载自www.cnblogs.com/yhxcs/p/12117080.html