Search code examples
c++functionarguments

C/C++ overwriting function argument that is a text pointer


I found this construct which I'm not sure if it's valid.

#include <iostream>
#define DEFAULT_TEXT "hello world"

void print_text(const char* custom_text) {

    if(!custom_text) {
        custom_text = DEFAULT_TEXT;
    }

    std::cout << custom_text << std::endl;
}

int main() {
    print_text(nullptr);
    return 0;
}

This compiles without error and its output is "hello world" as expected.

The function argument is a variable containing a pointer. By calling the function it contains a nullptr. Within the function the argument variable is overwritten with a pointer to the default text "hello world". That is defined by a preprocessor macro and expanded within an if statement that has limited scope within the if block.

Is this a valid stable construct? What's about the terminating null character of "hello world"? Have I to add one?


Solution

  • Yes, it's valid (though not great style in some ways).

    custom_text is a parameter, which makes it a local variable inside the function print_text(). A parameter is initialized with the value of the corresponding argument in the call (nullptr in this case).

    A function is free to change the values of any of its local variables.

    A C-style string includes a terminating null character '\0'. You don't need to worry about it, since it's implicit in the string literal "hello world".

    It would probably be better style to use std::string rather than raw C-style strings, but C++ deals with C-style strings without too many problems.

    You could also define your function with a default parameter value rather than writing that logic in the body of the function.

    One thing you should change is to delete the semicolon in the macro definition. The semicolon becomes part of the expansion of the macro, so your statement

    custom_text = DEFAULT_TEXT;
    

    becomes

    custom_text = "hello world";;
    

    The extra semicolon doesn't happen to cause any problems in this case, but it could result in a syntax error or worse in other contexts. The expansion of your macro should be a valid expression. (Macros can expand to other things, but expressions are perhaps the most common case.)