Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!milano!cadillac!puma!vaughan From: vaughan@puma.cad.mcc.com (Paul Vaughan) Newsgroups: comp.lang.c++ Subject: const Message-ID: <10863@cadillac.CAD.MCC.COM> Date: 4 Sep 90 23:02:49 GMT Sender: news@cadillac.CAD.MCC.COM Lines: 58 Awhile back I posted a message asking if const was really worth the trouble. Everyone who replied either on the net or privately thought that making a program const correct was indeed worth the effort. These were all pretty subjective opinions--it's kind of hard to measure how much difference it makes. So, here's a const question. Consider the following function const char* substring(const char* string, const char* sub) // substring searches for the first occurence of sub in string and //returns a pointer to it or 0 if none is found. { ....} If I'm working on a const char* (and, therefore, don't plan on changing any part of it) this works just fine. However, if I'm working on a char* and was planning to change part of it and was using substring to find that part, this will cause a problem because substring returns a const. For example, char* foo = "barfoobar"; *substring(foo,"foo") = `\0`; will give an error due to the modification of a non-const return value. I can't declare substring as char* substring(const char* string, const char* sub) because it is returning a pointer to part of the string that is passed in. I would declare it char* substring(char* string, const char* sub) but then I can't use it to deal with const char*'s, and, of course, I can't overload it based on the return type! So what do I do? My solution so far has been to declare it const char* substring(const char* string, const char* sub) and when I want to work on a char*, I do a cast, like this char* foo; char* bar = (char*) substring(foo, "foo"); Given the semantics of the function and that I'm passing in a char*, I can verify the safety of the cast without much trouble. Is there a better way? Paul Vaughan, MCC CAD Program | ARPA: vaughan@mcc.com | Phone: [512] 338-3639 Box 200195, Austin, TX 78720 | UUCP: ...!cs.utexas.edu!milano!cadillac!vaughan