string or const char * in a function parameter list ?

I

iu2

Hi all,

I find myselft wondering about the recommended way to pass strings to
functions:

int func(string s);

or

int func(const char *s);

I usually pass a const char * since it's shorter referring to s
instead of s.c_str() inside 'func'. In case some string manipulation
need arises, I can always launch a string or a stringstrem insinde
'func'.
Is there a good reason to pass a 'string' instead of a const char * ?

thanks
iu2
 
N

Neelesh Bodas

Hi all,

I find myselft wondering about the recommended way to pass strings to
functions:

int func(string s);

or

int func(const char *s);

I usually pass a const char * since it's shorter referring to s
instead of s.c_str() inside 'func'. In case some string manipulation
need arises, I can always launch a string or a stringstrem insinde
'func'.
Is there a good reason to pass a 'string' instead of a const char * ?


Using string class is much much much safer than using bare character
pointers.
http://www.parashift.com/c++-faq-lite/containers.html#faq-34.1
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.5

-N
 
J

john.papaioannou

First of all, you should not pass a string object by value most of the
time. If your function is not going to modify the string then you
should pass a const string& to avoid a copy of the object being made
(if you are passing a const char* as in your other example it means
that you are definitely not going to modify the string).

That said, if you have to ask the question then you should be using a
string of some sort instead of a const char*. It's much safer this
way.

Of course, if the program is really simple or you have a need for
speed, then char* can be a better choice.
 
T

tragomaskhalos

Hi all,

I find myselft wondering about the recommended way to pass strings to
functions:

int func(string s);
or
int func(const char *s);

Firstly, do not use the first form: prefer (const string&).
With that fix in place, I would say it depends on a number of factors:
1. If func needs the facilities of std::string, provide the const
string& form
2. If you envisage that a lot of calling code will use C-style
strings, provide
the const char* form.

Finally, it's easy enough to provide both and delegate; where you put
the
'meat' of the processing depends on what func actually does: Either:

int func (const string& s) { .... }
int func (const char* s) { return func(string(s)); }

Or

int func (const string& s) { return func(s.c_str()); }
int func (const char* s) { ... }

Cheers.
 

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

Forum statistics

Threads
474,201
Messages
2,571,051
Members
47,656
Latest member
rickwatson

Latest Threads

Top