What is the difference between char * const and const char *?

前端 未结 19 1153
执笔经年
执笔经年 2020-11-22 03:31

What\'s the difference between:

char * const 

and

const char *
相关标签:
19条回答
  • 2020-11-22 03:57

    Rule of thumb: read the definition from right to left!


    const int *foo;

    Means "foo points (*) to an int that cannot change (const)".
    To the programmer this means "I will not change the value of what foo points to".

    • *foo = 123; or foo[0] = 123; would be invalid.
    • foo = &bar; is allowed.

    int *const foo;

    Means "foo cannot change (const) and points (*) to an int".
    To the programmer this means "I will not change the memory address that foo refers to".

    • *foo = 123; or foo[0] = 123; is allowed.
    • foo = &bar; would be invalid.

    const int *const foo;

    Means "foo cannot change (const) and points (*) to an int that cannot change (const)".
    To the programmer this means "I will not change the value of what foo points to, nor will I change the address that foo refers to".

    • *foo = 123; or foo[0] = 123; would be invalid.
    • foo = &bar; would be invalid.
    0 讨论(0)
提交回复
热议问题