implicit vs. explicit type conversion for string vs. (char *)

  • Thread starter dmoos AT esigma-systems DOT de
  • Start date
D

dmoos AT esigma-systems DOT de

Hopefully somebody could teach me, what coding is correct,
clean and preferable:

#include <string>

int main(int argc, char **argv) {
std::string str = "lala";
char *cp = "lala";

return (cp == str) ? 0 : 1;
}

Is this code-snippet correct and ANSI-conform or should i
convert/copy/assign the content of cp into a string before
comparing to str?

All comments, hints and critics are highly appreciated.

Thanks in advance,

Darius.
 
R

Ron Natalie

dmoos AT esigma-systems DOT de said:
Is this code-snippet correct and ANSI-conform or should i
convert/copy/assign the content of cp into a string before
comparing to str?

There are operator== overloads in the standard library that
take combinations of string and char* and do the right thiing.
 
D

Default User

dmoos said:
#include <string>

int main(int argc, char **argv) {
std::string str = "lala";
char *cp = "lala";

return (cp == str) ? 0 : 1;
}

Is this code-snippet correct and ANSI-conform or should i
convert/copy/assign the content of cp into a string before
comparing to str?


Others have discussed the string comparison. I'll take this opportunity
to point out that returning anything from main() except for 0,
EXIT_SUCCESS or EXIT_FAILURE (inclusion of stdlib.h or cstdlib required
for the latter two) leads to implementation-specific results. For
maximum portability, don't return anything else (like 1) from main().




Brian Rodenborn
 

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,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top