一篇文章搞懂c语言常量与指针的几个排列组合

这个也是一个比较经典的面试题。也很多人挺纠结的,而且我发现挺多人搞不清楚的。

这里先说几个结论,后面在细细验证

  1. const int 和 int const是一样的。编译器都认为是int const类型
  2. 星号,以及星号之后的内容,只修饰右侧的一个变量

所以很简单了

  1. 指向int常量的指针 const int *a , int const * a,都是对的
  2. 指向int的常量指针int * const a
  3. 指向int常量的常量指针 const int * const a 或者int const * const a

下面是代码分析。

我写了一个简单的代码,将几个组合排列都列出来了,并且标出了编译错误和告警,有兴趣的朋友可以看一下。有错误的地方都被注释掉了,如果想自己重现,可以自己去掉注释然后编译,我使用的是clang,编译错误比较友好,如果使用gcc,错误会有不一样。

int main(int argc, char *argv[])
{
    
    int i = 0;
    int j = 0;
    const int a = 1, a1 = 2 ;
    int const b = 1, b1 = 2 ;
    const int * const const_int_ptr_const = &i;
    const int * const_int_ptr = &i
        , const_int = &i; //compile warning: incompatible pointer to integer conversion initializing 'const int' with an expression of type 'int *'
    int const * int_const_ptr = &i
        , int_const = &i; //compile warning: incompatible pointer to integer conversion initializing 'const int' with an expression of type 'int *'
//    const * int const_ptr_int = &i; //compile error
    int * const int_ptr_const = &i
        , int_ptr = &i; //compile warning: incompatible pointer to integer conversion initializing 'int' with an expression of type 'int *'
//    * int const ptr_int_const = &i; //compile error
//    * const int ptr_const_int = &i; //compile error

//    a = 2; //compile error: cannot assign to variable 'a' with const-qualified type 'const int'
//    a1 = 3;//compile error: cannot assign to variable 'a' with const-qualified type 'const int'
//    b = 4;//compile error: cannot assign to variable 'a' with const-qualified type 'const int'
//    b1 = 5;//compile error: cannot assign to variable 'a' with const-qualified type 'const int'


//    *const_int_ptr = 4; //compile error:read-only variable is not assignable
//    *int_const_ptr = 5; //compile error:read-only variable is not assignable
    *int_ptr_const = 6;
//    *const_int = 7; //compile error: indirection requires pointer operand ('int' invalid)
//    *int_const = 8; //compile error: indirection requires pointer operand ('int' invalid)
//    *int_ptr = 9;  //compile error: indirection requires pointer operand ('int' invalid)
//    *const_int_ptr_const = 10; //compile error: read-only variable is not assignable

    const_int_ptr = &j;
    int_const_ptr = &j;
//    const_int_ptr_const = &j; //compile error: cannot assign to variable 'const_int_ptr_const' with const-qualified type 'const int *const'

//    int_ptr_const = &j; //compile error: cannot assign to variable 'int_ptr_const' with const-qualified type 'int *const'

    return 0;
}


猜你喜欢

转载自blog.csdn.net/zerooffdate/article/details/79511503