-2

in the snippet code bellow when I pass a literal string to the function it gives me a warning ISO C++ forbids converting a string constant to 'char*but when I assign a character array to this literal the warning will be gone. I know that the type of string literals in C++ is constant character array but the type of ch variable is just char.(not constant char)

#include <iostream>

using namespace std;

void func(char s[])
{
    cout << s;
}
int main() {
    char ch[] = "what";
    func(ch);
    func("what"); //gives warning
    return 0;
}

and I have one question more. when I add const to input parameter type of func function there is no warning in this situation too even though I pass a character array to the function not const character array.I thought it should cause a warning for fucn(ch) call because ch is a character array not constant character array.

#include <iostream>

using namespace std;

void func(const char s[])
{
    cout << s;
}
int main() {
    char ch[] = "what";
    func(ch);
    func("what");
    return 0;
}
Shepesh
  • 1
  • 1
  • 1
    Possible duplicate of [Why do compilers allow string literals not to be const?](https://stackoverflow.com/questions/3075049/why-do-compilers-allow-string-literals-not-to-be-const) –  Jul 03 '18 at 03:08

1 Answers1

0

const is not about matching exactly, but about what the function is doing to the parameter.

If you define a function with a const parameter, the function promises to not change the passed variable. Therefore, you can call it with constant strings as well as (changable) non-constant variables. The compiler will warn you if you try to modify the value inside the function (because you promised you wouldn't).

If you define a function with a non-constant parameter, it can change the parameter. Therefore, the compiler warns you if you pass a constant string, as that would lead to undefined behavior / crashes.

Aganju
  • 6,295
  • 1
  • 12
  • 23
  • so what about the warning? `forbids converting a string constant to 'char*` I think there occurs some convertion. – Shepesh Jul 03 '18 at 03:02
  • A `char[]` array is _not_ a 'string'. Any array `T[]` automatically converts to `T*` where needed. That's actually one of the reason these kind of arrays are discouraged; use `std::array<>` instead. – Aganju Jul 03 '18 at 03:47
  • @Shepesh a string literal might not be stored in a writable memory region. Passing that string to a function that could write to the string literal's storage is a bad idea. Crom only knows what will happen. Program could crash, could ignore the write, could summon Cthulhu forth from R'lyeh and result in the eternal damnation of all mankind. The first two are more likely than the latter. See [Undefined Behaviour](https://en.wikipedia.org/wiki/Undefined_behavior). – user4581301 Jul 03 '18 at 04:36