next up previous contents
Next: Non-Constant char*: attach() and Up: char* Conversions Previous: Str Indexing   Contents

Constant char*

You can convert a Str to a const char* at any time by simply doing a C or C++-style cast. The cast operator simply returns the value of Str::data and is therefore very fast.

    Str x = "Hello";
    char buff[64];

    // Here are C-style cast examples
    printf("%s\n", (const char*)x);
    strcpy(buff, x);
    printf("strlen(x) = %u, x.length(x) = %u\n", strlen(x), x.length());

    // Here is a C++-style cast
    printf("%s\n", static_cast<const char*>(x));

One thing to note in the example above is that we only had to explicitly use the cast operator when making the call to printf(). This is because printf does not know the type of its arguments and needs a little help. In the strcpy() and strlen() cases, a cast was not required because these directly take const char* as an argument. It is, of course, OK to explicitly cast in these cases anyway if you believe it improves the clarity of the code.

Also, even though strlen(x) and x.length() in the above return the same answer, x.length() does so much more quickly because strlen() has to walk the string to find the length. A basic principle here is that, if a function exists in Str(), there is a good chance it is taking advantage of the Str::size_and_flags field to accelerate the operation.


next up previous contents
Next: Non-Constant char*: attach() and Up: char* Conversions Previous: Str Indexing   Contents
2007-05-05