Double const declaration

后端 未结 8 1491
花落未央
花落未央 2021-02-05 13:20

I often see the following function declaration:

some_func(const unsigned char * const buffer)
{

}

Any idea why the const is repeated before th

相关标签:
8条回答
  • 2021-02-05 13:45

    The first const says that the data pointed to is constant and may not be changed whereas the second const says that the pointer itself may not be changed:

    char my_char = 'z';
    const char* a = &my_char;
    char* const b = &my_char;
    const char* const c = &my_char;
    
    a = &other_char; //fine
    *a = 'c'; //error
    b = &other_char; //error
    *b = 'c'; //fine
    c = &other_char; //error
    *c = 'c'; //error
    
    0 讨论(0)
  • 2021-02-05 13:46

    It's a constant pointer to a constant unsigned char. You can't change the pointer nor the thing it points to.

    0 讨论(0)
提交回复
热议问题