Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion from char** to const char**

Why my compiler(GCC) doesnt implicitly cast from char** to const char**?

Thie following code:

#include <iostream>

void print(const char** thing) {
    std::cout << thing[0] << std::endl;
}

int main(int argc, char** argv) {
    print(argv);
}

Gives the following error:

oi.cpp: In function ‘int main(int, char**)’:
oi.cpp:8:12: error: invalid conversion from ‘char**’ to ‘const char**’ [-fpermissive]
oi.cpp:3:6: error:   initializing argument 1 of ‘void print(const char**)’ [-fpermissive]
like image 798
André Puel Avatar asked Aug 10 '11 18:08

André Puel


1 Answers

Such a conversion would allow you to put a const char* into your array of char*, which would be unsafe. In print you could do:

thing[0] = "abc";

Now argv[0] would point to a string literal that cannot be modified, while main expects it to be non-const (char*). So for type safety this conversion is not allowed.

like image 73
sth Avatar answered Sep 28 '22 05:09

sth