non-const default char* argument

Greetings,
i'm making a function with an option argument which must be a string. Is there any way to do that without having the string as const char*? (i'd prefer to not use the string type).

Usage example:

void function(int a, int b = 0, char* str = "default") {}
yep.

char blah[] = "text";

foo(..., blah, etc); //blah is a non const pointer here, but you should not attempt to re-assign the pointer or bad things will happen. You can change the string data, of course. It IS effectively a const pointer, but the const is lost in the shuffle, and that isnt really a good thing but it does what you asked for.

you could also say
char *str = 0

and then handle the pointer depending on whether it was null or over-ridden by the user...
Last edited on
You cannot legally do
char* str = "string literal";
in C++.

To give a better answer, we'd need to know more about how you're using the data. Is sounds like you want to modify the string? You can't modify string literals.

Going off what jonnin said, but with a slight change, maybe you want something like this...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Example program
#include <iostream>

void function(int a, char* str)
{
    str[0] = 'b';
    std::cout << a << " " << str << "\n";
}

void function(int a)
{
    char str[] = "default";
    function(a, str);
}

int main()
{
    // test 1
    function(42);
    
    // test 2
    char str[] = "custom";
    function(42, str);
}


Topic archived. No new replies allowed.