Should I use char over string for immutable strings?

I'm making an arithmetic parser which would have a static input.

So should I use
int parser(const *char[] = "5+5+5") {}
or
int parser(string *char = "5+5+5") {}
or is there something better?

I have heard that strings are slower than arrays. And in this case using string wouldn't give you an advantage over array would it? Since the string won't be changed.



Last edited on
Prefer std::string, even though you don't seem to know how to use them.

I have heard that strings are slower than arrays.


This is an old wives tale from the early days of the language.

And in this case using string wouldn't give you an advantage over array would it?


A std::string has many advantages of a C-string. For one your function call using the C-string is really incorrect, you should be passing the size of the string into that function as well.

Since the string won't be changed.

A std::string has many different member functions to help "parse" that string that are much safer to use than the c-string counterparts.
Umgh can you use a pointer to point to a string? That doesn't seem to work..
Umgh can you use a pointer to point to a string? That doesn't seem to work..

Of course you can. There's nothing magical about the std::string class that stops you being able to have pointers to them.

"That doesn't seem to work" is useless as a statement of your problem. If you're talking about your line:

int parser(string *char = "5+5+5") {}

you're presumably getting compiler errors, because char is a reserved keyword, and you can't use it as the name of a variable.
Last edited on
int parser(const *char[] = "5+5+5") {} //this won't compile either, for similar reasons. ^^

It seems to be a tossup depending on exactly what you are doing whether string or c-string is faster. May even be compiler by compiler. Its not exactly a wive's tale, its just that back when the STL was new, you had a double hit of suboptimal libraries (vector was HORRID in the early days) combined with much, much, much slower hardware. There is no justification for using c-strings now; even if talking to other code that is in C or uses C-strings you can pull out what you need from string and feed it to the library without having to actually use c-strings. If you want a string constant, consider what we saw in another thread ... the s suffix. "5+5+5"s is a c++ string constant; you can put it in a const expression. The only c-string thing I will do anymore is the occasional printf to format lots of floating point with less gibberish, and that is a personal choice combined with age and stubbornness :)
Last edited on
Topic archived. No new replies allowed.