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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • dmoos AT esigma-systems DOT de

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

    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.
  • Ron Natalie

    #2
    Re: implicit vs. explicit type conversion for string vs. (char *)


    "dmoos AT esigma-systems DOT de" <pfffffrrrrt@gm x.de> wrote in message news:bdegjr$s4b e3$1@ID-193014.news.dfn cis.de...
    [color=blue]
    > 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?[/color]

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


    Comment

    • Default User

      #3
      Re: implicit vs. explicit type conversion for string vs. (char *)



      dmoos AT esigma-systems DOT de wrote:
      [color=blue]
      > #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?[/color]


      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

      Comment

      Working...