473,803 Members | 3,416 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 34601
On 2008-08-06 19:28:36 -0400, Juha Nieminen <no****@thanks. invalidsaid:
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).
This overlooks another overbroad principle: const_cast should be used
to adjust constness; using other casts for that purpose should be
avoided.

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

Aug 7 '08 #21
On Aug 7, 1:28 am, Juha Nieminen <nos...@thanks. invalidwrote:
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).
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_cas t 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_cas t". That's just wrong.
Agreed. Using static_cast or reinterpret_cas t to adjust
const-ness, even when they allow it (i.e. adding const) is just
wrong.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Aug 7 '08 #22
Pete Becker wrote:
On 2008-08-06 14:19:43 -0400, kwikius <an**@servocomm .freeserve.co.u k>
said:
>>
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.
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/...c3/node10.html

Am I doing something not allowed? If so, how to fix?
Aug 7 '08 #23
On 2008-08-07 04:14:03 -0400, James Kanze <ja*********@gm ail.comsaid:
>
-- If you use static_cast, you can't accidentally add const
But you can. <gThe prohibition is that "The static_cast operator
shall not cast away constness...". [expr.static.cas t]/1.

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

Aug 7 '08 #24
On 2008-08-07 04:43:44 -0400, anon <an**@no.nosaid :
Pete Becker wrote:
>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.

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[] )
Why? "char *argv[]" is the usual form.
{
...

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

glutInit function is described here:
http://www.opengl.org/documentation/...c3/node10.html

Am I doing something not allowed? If so, how to fix?
No, it's allowed. But it's contradictory: the declaration of main says
that the chars in the argument array are not modifiable, then later on
the cast says that they are. Make up your mind.

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

Aug 7 '08 #25
James Kanze wrote:
>You may as well say "if you want to add constness eg. for
overload resolution, use reinterpret_cas t". That's just wrong.

Agreed. Using static_cast or reinterpret_cas t 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.
Aug 7 '08 #26
In article <g7**********@n ews01.versatel. de>, anon <an**@no.nowrot e:
>Pete Becker wrote:
>On 2008-08-06 14:19:43 -0400, kwikius <an**@servocomm .freeserve.co.u k>
said:
>>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.
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 );
...
}
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. So if the const_cast
was added because of that mistake, then the const_cast is a mistake.
Which, once again points to the dangers of casting, adding cast to
get around errors, etc. Now, assuming this was some other function
and not main and assuming the arguments are of those type, then yes,
a const_cast<like that might make sense.

BTW, there is also a side issue about declaring argc const.
The usual argument is that a top level const parameter does not lend
to the interface of function, therefore, it should not be there.
I'm not saying one is right and one is wrong (though others here
might :} ), just putting the issue on the table as you will no doubt
eventually run across it.
--
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 7 '08 #27
On Aug 7, 10:43 am, anon <a...@no.nowrot e:
Pete Becker wrote:
On 2008-08-06 14:19:43 -0400, kwikius <a...@servocomm .freeserve.co.u k>
said:
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.
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/...c3/node10.html
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.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Aug 8 '08 #28
On Aug 7, 5:42 pm, com...@panix.co m (Greg Comeau) wrote:
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".)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Aug 8 '08 #29
On Aug 7, 12:19 pm, Pete Becker <p...@versatile coding.comwrote :
On 2008-08-07 04:14:03 -0400, James Kanze <james.ka...@gm ail.comsaid:
-- If you use static_cast, you can't accidentally add const
But you can. <gThe prohibition is that "The static_cast operator
shall not cast away constness...". [expr.static.cas t]/1.
That's a typo. I meant to say that you can't accidentally
remove const.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Aug 8 '08 #30

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
2192
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
9565
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10317
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...
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...
1
7604
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6844
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
5501
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
5633
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
3
2972
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.