Default argument pointer

Hello, I will pass an argument to function. I need compute int and string in this function; after int, string and bool in same function.
I make this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void fn(string*, int*, bool* pbool=false)
{
    // bla-bla-bla
    *pbool = true;
}
string str;
int ival_1[] = { 0, 0, 0 };
for (int i=0; i<3; i++)
{
    fn(&str, &ival_1[i]);
}
int ival_2[] = { 0, 0, 0, 0 };
bool bval[] = { false, false, false, false };
for (int i=0; i<4; i++)
{
    fn(&str, &ival_2[i], &bval[i]);
}

but return "default segmentation" in line 4. I think do a struct { string, int, bool } or declare the non-used variable
1
2
3
4
5
bool non_used = false;
for (int i=0; i<3; i++)
{
    fn(&str, &ival[i], &non_used);
}

but I will without this, it is possibly?
1
2
3
4
5
6
7
// void fn(string*, int*, bool* pbool=false)
void fn(string*, int*, bool* pbool = 0 )
{
    // bla-bla-bla
    // *pbool = true;
    if( pbool != 0 ) *pbool = true; 
}
If you're passing in a pointer, you can only specify the default value of the actual pointer itself - i.e. the memory address which the pointer will be pointing to. Unless your default is 0 (i.e, NULL), that's inherently dangerous.

If you want to set a default value on the input parameter, and still pass back a new value for the parameter, the simplest way would be to have your function take a plain bool as an input (with a default value), and return the new value:

1
2
3
4
5
6
7
bool fn(string*, int*, bool pbool = false)
{
    // bla-bla-bla
    pbool = true; 

    return pBool;
}



Last edited on
Thanks. I do the bool fn(bla-bla).
Compiler not convert 0 to false?
Last edited on
Compiler not convert 0 to false?

If an integer expression is being cast/converted to a bool expression then, yes, 0 will convert to false, and any non-0 value will convert to true.
false is a literal; it is an integral constant prvalue that evaluates to zero (at compile time).
It can be used as a null pointer constant.

1
2
3
4
5
6
7
8
9
10
11
12
13
bool* pointer ;

// all these set the pointer to a null pointer
pointer = nullptr ;
pointer = 0 ;
pointer = false ; // *** warning: converting 'false' to pointer type
pointer = int(false) ;
pointer = 0ULL ;
pointer = int(0.0) ;
pointer = false + 0 ;

// this is an error
pointer = 0.0 ; // *** error: 0.0 is not an integral constant expression 
Topic archived. No new replies allowed.