converting a char* to a const char*

S

Sean Farrow

Hi:
What is best and safest way of converting a char* to a const char *? Can I
use const_cast?
Cheers
Sean.
 
P

Pascal J. Bourguignon

Sean Farrow said:
Hi:
What is best and safest way of converting a char* to a const char *? Can I
use const_cast?

#include <iostream>
int main(){
char* c=new char[3];

const char* cc=c; // It's that simple!

c[0]='a';c[1]='b';c[2]=0;
std::cout<<cc<<std::endl;
return(0);
}
 
K

kwikius

Sean said:
Hi:
What is best and safest way of converting a char* to a const char *? Can I
use const_cast?

No const_cast is rather technical and best not used (unless you *really*
understand what its purpose is). In a nutshell, if you have an object
that you know is not const but it appears as const via e.g a function
argument then you can use const_cast, otherwise you can't. IOW it
removes constness in the case where you know that a variable is in
memory and isnt constant, however for constants that realy are constant
it can have nasty efects. As its quite rare to know this much about what
a variable is except in private member functions and so on its rare to
need it.

regards
Andy Little
 
S

Sean Farrow

Hi:
it's a function call needing a const char*, I assume from your description,
then const_cast can be used.
Sean.
 
J

Juha Nieminen

Sean said:
What is best and safest way of converting a char* to a const char *? Can I
use const_cast?

You have got it backwards: const_cast is used to *remove* constness,
not to add it.

You don't need to do anything special to add constness to a pointer.
Anything that expects a const pointer can be given a non-const one.
 
E

Eberhard Schefold

Sean said:
it's a function call needing a const char*, I assume from your description,
then const_cast can be used.

void f( const char * );

....

void g( char * p )
{
f( p );
}


I fail to see where the problem is that you're trying to solve with
const_cast. Could you give a code example?
 
S

Sean Farrow

Hi:
I've solved the issue, it was const_cast I needed, that's going to teach me
to rad error info properly.
Thanks to everybody.
Sean.
 
J

James Kanze

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. Most of the
time. of course, you don't bother, since the compiler will
happily add all the consts you want, if needed.
You don't need to do anything special to add constness to a
pointer. Anything that expects a const pointer can be given a
non-const one.

For first-level const. You can't pass a char** to a function
expecting a char const**.
 
K

kwikius

Hi:
it's a function call needing a const char*, I assume from your description,
then const_cast can be used.

Nope! Dont bother with it. make a copy of the string or use
std::string.

regards
Andy Little
 
K

kwikius

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
 
P

puzzlecracker

const_cast can be used to add or> remove const;

How can const_cast add constantness? I was under impression that it
only remove constantness if object is "not really" constant.
 
I

Ian Collins

puzzlecracker said:
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<const int*>(p);

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

Juha Nieminen

Sean said:
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.)
 
J

Juha Nieminen

James said:
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_cast". That's just wrong.
 
J

James Kanze

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).

That's a good point. As Pete said, const_cast is for adjusting
const, and that's what you're doing. But IMHO, it's arguable
both ways:

-- If you use static_cast, you can't accidentally add const
(but is this really a problem?). Also, it won't show up if
someone greps for const_cast (which they're doubtlessly
doing to find "dangerous" code, and adding const isn't
dangerous).

-- If you use const_cast, you can't accidentally perform a
Derived* to Base* (or worse, a Base* to Derived*) conversion
which you didn't want.

IMHO, that second point predominates, and is, ultimately, the
reason why the new style casts were introduced: const_cast
allows adjusting const-ness, with no risk of accidentally
performing any other conversion, static_cast allows moving up
and down in the hierarchy, without any risk of accidentally
removing const-ness or type punning, and reinterpret_cast forces
type punning (even if the types involved are pointers within an
inheritance hierarchy), without any risk of removing const-ness.
You may as well say "if you want to add constness eg. for
overload resolution, use reinterpret_cast". That's just wrong.

Agreed. Using static_cast or reinterpret_cast to adjust
const-ness, even when they allow it (i.e. adding const) is just
wrong.
 
A

anon

Pete said:
Agreed. It's an advanced feature, and beginners shouldn't use it.

Do you have a link to good article explaining const_cast, cause I never
read anything similar.

I am asking, because in my application is like this:

int main( const int argc, const char* argv[] )
{
....

int arg1 = argc;
char** arg2 = const_cast< char** > ( &argv[0] );
glutInit( &arg1, arg2 );
....
}

glutInit function is described here:
http://www.opengl.org/documentation/specs/glut/spec3/node10.html

Am I doing something not allowed? If so, how to fix?
 
J

Juha Nieminen

James said:
Agreed. Using static_cast or reinterpret_cast to adjust
const-ness, even when they allow it (i.e. adding const) is just
wrong.

Intentionally misinterpreting someone's text, even if it's clearly a
pun, is annoying.
 
J

James Kanze

Do you have a link to good article explaining const_cast,
cause I never read anything similar.
I am asking, because in my application is like this:
int main( const int argc, const char* argv[] )
{
...
int arg1 = argc;
char** arg2 = const_cast< char** > ( &argv[0] );
glutInit( &arg1, arg2 );
...
}
Am I doing something not allowed? If so, how to fix?

Yes. That's not a standard definition of main. The two
standard definitions are:
int main()
and
int main( int argc, char** argv )
Anything else is an implementation extension, if it works at
all.

I wonder: why don't compilers complain about versions of main
they don't support? I just compiled a
int main( double d ){}
, and none of the compilers I use even output a warning.
Although I'm pretty sure that if I tried to use the d, I'd just
get garbage. The behavior in such cases is implementation
defined; there's no reason for an implementation to not generate
an error if it doesn't support the definition. (IMHO, this
would be far more useful than forbidding "void main()", despite
the fact that it more or less works.)
 
J

James Kanze

This is well somewhat confusing, though useful :) as main
normally doesn't take arguments declared that way. In
specific, argc and argv and *argv and **argv etc are all
modifiable.

Is this an intentional change from C, or something that just
slipped through. (In C, the type of argv is char**, but the
application isn't allowed to modify the pointers in the array
pointed to by argv---although it is allowed to modify argv
itself, and the strings the pointers point to: "argv=p" is
legal, as is "argv[1][0]='\0' (provided that argc >= 2), but not
"argv[1]=p".)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top