Difference between const char*, char const*, const char const* & string storage

后端 未结 6 1814
后悔当初
后悔当初 2020-12-24 15:50

First of all, what\'s the difference between:

(1) const char*
(2) char const*
(3) const char const*

I\'m fairly certain I understand this f

6条回答
  •  情深已故
    2020-12-24 16:17

    1 and 2 are equivalent, and specify the type of a pointer to a const char. The pointer itself is not const. 3 is invalid, because it repeats "const". It's like saying const const int. The order is not relevant, so it's also like saying int const int.

    In C99 it is valid to repeat const like that. But in C++, you cannot repeat it.

    Also, how are string-literalls stored by the compiler?

    They are stored in an unspecified way. But compilers are allowed to store them in a read-only portion of the program. So you cannot write to string literals. You are guaranteed that they stay allocated through the whole program lifetime (in other words, they have static storage duration).

    This isn't homework, I'm just brushing up on C for interviews in case anyone cares.

    You should be aware of the subtle differences between C and C++. In C99, like explained above, const const int is allowed. In C89 and C++ it is forbidden. In C++ you can however introduce a redundant const, if applied to a typedef that is itself const:

    typedef int const cint;
    cint const a = 0; // this const is redundant!
    

    Same goes for template parameters.

提交回复
热议问题