473,803 Members | 3,637 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

converting a char* to a const char*

Hi:
What is best and safest way of converting a char* to a const char *? Can I
use const_cast?
Cheers
Sean.
Aug 6 '08
35 34600
On 2008-08-06 13:47:32 -0400, kwikius <an**@servocomm .freeserve.co.u ksaid:
On Aug 6, 3:10Â*pm, "Sean Farrow" <sean.far...@se anfarrow.co.ukw rote:
>Hi:
it's a function call needing a const char*, I assume from your descriptio
n,
>then const_cast can be used.

Nope! Dont bother with it. make a copy of the string or use
std::string.
Wait, I'm confused. If the situation is this:

void f(const char *);

void g(char *p)
{
// how to call f with the character array that p points to?
}

Then the answer is far simpler: just do it. f(p) relies on the implicit
conversion of char* to const char*. No need for const_case, copying, or
std::string.

Of course, if the situation is something different, then the answer is
almost certainly different. <g>

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Aug 6 '08 #11
On Aug 6, 7:03*pm, Pete Becker <p...@versatile coding.comwrote :
On 2008-08-06 13:47:32 -0400, kwikius <a...@servocomm .freeserve.co.u ksaid:
On Aug 6, 3:10*pm, "Sean Farrow" <sean.far...@se anfarrow.co.ukw rote:
Hi:
it's a function call needing a const char*, I assume from your descriptio
n,
then const_cast can be used.
Nope! Dont bother with it. make a copy of the string or use
std::string.

Wait, I'm confused. If the situation is this:

void f(const char *);

void g(char *p)
{
* * * * // how to call f with the character array that p points to?

}

Then the answer is far simpler: just do it. f(p) relies on the implicit
conversion of char* to const char*. No need for const_case, copying, or
std::string.
hmm.. Apologies to the O.P. I wasnt aware that const_cast can be used
to cast to const. And rereading the post it seems that what he wanted.

The idea that its ok to cast away const in general use with const_cast
is bad. From time to time one gets an error message related to trying
to use a value that is passed as a constant ref sa non const. In this
situation one temptation is to use const_cast. However the real answer
is to try to find out what the problem is with the design or your
understanding of the function.

In writing a function Since the user of the function doesnt expect
the value to be changed in the function, there is no reason to use
const_cast. If you are going to write to a reference then make that
clear.

Problem is that const_cast sometimes looks like a nice easy solution
to problems, which it isnt.

regards
Andy Little
Aug 6 '08 #12
On 2008-08-06 14:19:43 -0400, kwikius <an**@servocomm .freeserve.co.u ksaid:
>
Problem is that const_cast sometimes looks like a nice easy solution
to problems, which it isnt.
Agreed. It's an advanced feature, and beginners shouldn't use it.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Aug 6 '08 #13
>const_cast can be used to add orremove const;

How can const_cast add constantness? I was under impression that it
only remove constantness if object is "not really" constant.
Aug 6 '08 #14
>
For first-level const. *You can't pass a char** to a function
expecting a char const**.
First is the first level const?

Aug 6 '08 #15
puzzlecracker wrote:
>const_cast can be used to add orremove const;

How can const_cast add constantness? I was under impression that it
only remove constantness if object is "not really" constant.
int n;
int* p = &n;
const int* cp = const_cast<cons t int*>(p);

The const_cast is superfluous here, but legal. I'm sure someone can
contrive a template example where it would be required!

--
Ian Collins.
Aug 6 '08 #16
In article <38************ *************** *******@k30g200 0hse.googlegrou ps.com>,
puzzlecracker <ir*********@gm ail.comwrote:
const_cast can be used to add orremove const;
How can const_cast add constantness? I was under impression that it
only remove constantness if object is "not really" constant.
Probbaly where I've seen it pop up most is in changing the
type of the "this" pointer to force a const overloaded function
to be called instead of the non-const one.

Usual caveats apply: consider using it this way wisely,
consider any other alternatives, blah blah.

Also, I forget if using it this way is undefined behavior.
--
Greg Comeau / 4.3.10.1 with C++0xisms now in beta!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Aug 6 '08 #17
In article <ed************ *************** *******@2g2000h sn.googlegroups .com>,
puzzlecracker <ir*********@gm ail.comwrote:
>For first-level const. =A0You can't pass a char** to a function
expecting a char const**.

First is the first level const?
Dunno if this helps: http://www.comeaucomputing.com/techtalk/#deconstutoh
--
Greg Comeau / 4.3.10.1 with C++0xisms now in beta!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Aug 6 '08 #18
Sean Farrow wrote:
I've solved the issue, it was const_cast I needed, that's going to teach me
to rad error info properly.
Now that you have resolved the problem, could you also explain to us
the situation where you needed to use const_cast to *add* constness
(instead of removing it) so that also we can learn from it?

(Somehow I have the feeling that the const_cast is *not* the real
solution to your problem. It just happens to work, and masks the real
problem.)
Aug 6 '08 #19
James Kanze wrote:
>You have got it backwards: const_cast is used to *remove*
constness, not to add it.

Usually. It can be used either way, and there are times when
you want to explicitly add the const, to control overload
resolution, or template instantiation, for example.
Isn't that what static_cast is for? const_cast sounds like the wrong
tool for the job (because common C++ wisdom dictates that static_cast is
good and const_cast should usually be avoided if possible).

You may as well say "if you want to add constness eg. for overload
resolution, use reinterpret_cas t". That's just wrong.
Aug 6 '08 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5434
by: jagmeena | last post by:
Hello, I am sure this problem has been addressed before, however, I could'nt get a suitable solution to my problem. Hence I am posting here. Thanks a lot for all your help. The code I have is typedef struct Rec { unsigned char msg; unsigned long len;
20
2191
by: Nate | last post by:
I am working on an Oakley parser and want to call an fopen function to read in the log file. I can use this to read the file, but only if I pass a "const char" variable to fopen. Since I would like the end user to specify the name of the log file, I have a scanf in there to allow the user to do so, but it isn't a const at that point. I have seen reference to calls like static_cast, dynamic_cast and reinterpret_cast in C that will allow...
7
1976
by: jamihuq | last post by:
Hello, I would like to convert the following inline function to a macro. Can someone help? Thx Jami inline char * fromDESC(const char * &aDesC)
3
2187
by: fakeprogress | last post by:
How would I go about converting this C code to C++? /* LIBRARY is an array of structures */ /* This function compares 'tcode' with */ /* existing codes in the array. */ /* It returns the index of the code in */ /* the LIBRARY structure if it is found. */ int findcode( LIBRARY *b, int n, char *tcode ) { int i;
9
30527
by: Gregory.A.Book | last post by:
I am interested in converting sets of 4 bytes to floats in C++. I have a library that reads image data and returns the data as an array of unsigned chars. The image data is stored as 4-byte floats. How can I convert the sets of 4 bytes to floats? Thanks, Greg Book
2
10939
by: pookiebearbottom | last post by:
Just looking for opinion on which of the 3 methods below people use in their code when they convert a 'const char *' to a 'const std::string &' came across #3 in someone's code and I had to think for a sec. At first I read it as converting a 'const char *' to a 'std::string *' void f(const std::string &s) { std::cout << s.size() << "\n";
11
12787
by: hamishd | last post by:
Is this possible? Sorry if this question isn't relevant here. actually, I'm really trying to convert a unsigned char * to an int
5
12658
by: Hans Mull | last post by:
Hi! How can I convert a string to a const unsigned char*? (string::c_str() converts the string to a signed char) Thanks in advance, Hans
7
4789
by: ma740988 | last post by:
Consider the equation (flight dynamics stuff): Yaw (Degrees) = Azimuth Angle(Radians) * 180 (Degrees) / 3.1415926535897932384626433832795 (Radians) There's a valid reason to use single precision floating point types. The number of decimal digits guaranteed to be correct on my implementation is 6. (i.e numeric_limits < float >::digits10 = 6 ) If I'm reading the IEEE standard, I'd could paraphrase the issue
0
10316
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10295
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6842
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5500
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.