Adding const keyword to an array passed as a parameter to function

前端 未结 5 1024
死守一世寂寞
死守一世寂寞 2021-02-07 07:17

Is there any way that I can add const keyword to an array passed as a parameter to function:

void foo(char arr_arg[])

If I place <

5条回答
  •  感情败类
    2021-02-07 07:55

    The first thing is that in your particular signature, the argument is transformed by the compiler into a pointer, so what you have is:

    void foo( char * arg );
    

    Now, there are two entities that can be made const in that signature: the pointer and the pointed type. To make the pointed type can be made const in two different yet equivalent ways [*]:

    void foo( const char * arg );
    void foo( char const * arg );
    

    The pointer could be made const with the syntax:

    void foo( char * const arg );
    

    But note that in a function signature, in the same way that char arg[] is transformed into a pointer char *arg, the top level qualifier is discarded. So from the point of view of the declaration, these two are equivalent:

    void foo( char * const arg );
    void foo( char *       arg );
    

    In the definition, the top level const can be use to instruct the compiler that the argument pointer (by value) should not be changed within the function, and it will detect if you attempt to reset the pointer to a different location. But, if only the pointer is const, then the compiler will gladly let you modify the pointed memory. If you don't want the function to change the contents of the array, then you should opt for one of the first two signatures.

    [*] I tend to prefer the char const * format, as it provides a consistent way of reading types: from right to left it reads: a non-const pointer to a const char. Additionally it is simpler to reason about typedef-ed types (by performing direct substitution in the expression). Given typedef char* char_p;, const char_p and char_p const are both equivalent to char * const and different from const char *. By consistently using const on the right you can just blindly substitute the typedef and read the type without having to reason.

提交回复
热议问题