954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ const help

I'm not that used to C++ and hoping that someone can help me out with the const keyword. If I make a parameter to a function 'const' ,and then try to reference it, like:

int some_func(const char* param){
  char* ptr = param;
  ...
}

to do something with it, the compiler gives the "invalid conversion from const char* to char*" when I try to pass in a parameter. The question is, is there some way to reference the 'param' while keeping it constant? or how can I fix the error message? Thanks in advance

blackjack
Newbie Poster
2 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
 

Why not just use std::strings?

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

you can do this: char* ptr = const_cast<char*>(param;) , but that defeats the purpose of using const in the first place. Casting out the const should be avoided whenever possible.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Either using :

const char* ptr = param ;
// or
char* ptr = const_cast<char*> (param) ;


But it would be interesting to know what you are trying to achieve here.....

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

Basically, I need to step through any array using pointers instead of the array indices. I changed my char* ptr to const char* ptr and it does work. Thanks.

blackjack
Newbie Poster
2 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
 
Basically, I need to step through any array using pointers instead of the array indices. I changed my char* ptr to const char* ptr and it does work. Thanks.


But why would having a second const char* copy do you any good? Neither pointer can you modify, so copying it would be sort of pointless (sorry, bad pun).

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You