Search code examples
c++pointerscastingconstantsnullptr

c++ const char* to char*


I have the following function which initially performs some validation on function parameters.

char *doSomething(const char* first, const char* second) {

    if((first == nullptr || *first == '\0') && (second == nullptr || *second == '\0')) {
        return nullptr;
    } else if (first == nullptr || *first == '\0') {
        return (char *) second;
    } else if (second == nullptr || *second == '\0') {
        return (char *) first;
    }
    //doSomething
}

Does casting the function parameter return a new char* that points to a different area in memory? I don't want to allow someone using this function to manipulate the value that the constant parameters are pointing to. I would like a new char* to be returned with the same value as one of the parameters if one is nullptr or empty.

Follow-up: Would a boolean variable be better here? I realize I'm performing the same check for each variable twice, but I wouldn't be utilizing this boolean anywhere else in this function's code.


Solution

  • No it doesn't make any new object it simple casts away const to the area of memory you declared to be immutable. Which normally results in the dreaded Undefined Behavior but if they come from non-const pointer you'll be ok (EDIT - thanks to @anatolyg).