0

I have following code.

#include <iostream>

using namespace std;

int
main(int argc, char **argv) {
        const char *a ="123";
        constexpr const char *b ="123"; // g++ compile ok
        constexpr char *c ="123"; // g++ compile warning
        if (a == b) {
                cout << "a pointer is equal to b" << endl;
        } else {
                cout << "a pointer is not equal to b" << endl;
        }
}

Use g++ toolchain to compile. I am told that const char* is converted to char*.

constexpr char *c ="123";

Why doesnot constexpr cover the meaning of "const"?

⋊> /h/m/stackoverfolw g++ test7.cpp -std=c++11
test7.cpp: In function 'int main(int, char**)':
test7.cpp:9:21: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
constexpr char *c ="123";
^

mariolu
  • 346
  • 2
  • 11
  • 1
    Because `constexpr` and `const` mean different things? – Sam Varshavchik Mar 27 '21 at 16:52
  • `const char *c = "123"` means a pointer to const char. `char *c ="123"` is forbidden in C++. `constexpr` makes nothing with a pointed type, `constexpr char *c ="123";` is still fobiden. You can do `constexpr char c[] ="123";`. – S.M. Mar 27 '21 at 16:59
  • `constexpr char *c` bears greater similarity to `char * const c` than to `const char * c`. It declares the *pointer* to be `constexpr`, not the pointed-to object. – JaMiT Mar 27 '21 at 17:16

0 Answers0