0

I am learning C++ from a textbook (C++: A Beginnners Guide, Second Edition, Herbert Schildt). The following program code is from the book, but results in error, can someone please explain to me why this is not allowed?

The aim is to demonstrate a pointer as a parameter:

#include <iostream>

using namespace std;

char *get_substr(char *sub, char *str); //function prototype

int main()
{
    char *substr;
    substr = get_substr("three", "one two three four");

    cout << "substring found: " << substr;

    return 0;
}

I'll not list the function body because it goes as you would expect, but even if it just returns zero, this results in the following error: E0167 argument of type "const char *" is incompatible with parameter of type "char *", referencing the function call. My understanding is a string is basically an array of char in C anyway, why is this not allowed, and what is a suitable alternative? Thank you in advance.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • 3
    "C++: A Beginnners Guide, Second Edition, Herbert Schildt" - a great way NOT to learn C++ properly. –  Mar 13 '19 at 15:35
  • 1
    Oh yes, good old Schildt, teaches you language that is almost but not quite C++. – john Mar 13 '19 at 15:35
  • quoting [wikipedia](https://en.wikipedia.org/wiki/Herbert_Schildt) "Schildt's books have a reputation for being riddled with errors" – 463035818_is_not_an_ai Mar 13 '19 at 15:44

3 Answers3

6

Your book is old and doesn't conform to the standard anymore, as char* litterals must be const since C++11:

const char *get_substr(const char *sub, const char *str);

Have a look at the curated C++ book list.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
1

String literals like "three" are of const char [N] data-type. The arguments passed are not compliant with C++11 standards. The following usage should fix your issue

const char *get_substr(const char *sub, const char *str);

Here is a quick guide for you https://www.geeksforgeeks.org/difference-const-char-p-char-const-p-const-char-const-p/

0

Your compiler complains because you are feeding a string literal to a function that may want to modify it.

Presumably, your get_substr() function does not modify the input string, nor the string you are looking for (either of the parameters).

If you know this about your function, you can change its prototype to

const char *get_substr(const char *sub, const char *str);

This has following effects:

  • the compiler will complain if you try to modify either of the strings in the body of the function
  • the compiler will be free to assume that your function does not change the data and will not complain when you use const data (such as literals) as parameters for the function
Jan Remeš
  • 19
  • 1