Search code examples
c++arraysdefault

Set default value to C array when used as function argument


I have the following function:

void getDefaultMaterial(Uint8 rgb[3]);

The problem is that I want rgb argument to have default value. Like that:

void getDefaultMaterial(Uint8 rgb[3]={255, 255, 255});

Unfortunately, the compiler does not like this? Is there another way?


Solution

  • Note that the parameter is a pointer, not an array.
    To the compiler, the prototype is equivalent to

    void getDefaultMaterial(Uint8* rgb);
    

    Overloading is one alternative:

    void getDefaultMaterial(Uint8 rgb[3]);
    
    void getDefaultMaterial()
    {
        Uint8 rgb[3] = { 255, 255, 255 };
        getDefaultMaterial(rgb);
    }
    

    Although, if rgb is an "out" parameter, the point of this eludes me.

    If it's not an "out" parameter, you can use an actual array with a default value, but you need to pass it by const reference:

    void getDefaultMaterial(const Uint8 (&rgb)[3] = {255, 255, 255});
    

    or, as an "out" parameter with "default by overloading":

    void getDefaultMaterial(Uint8 (&rgb)[3]);
    
    void getDefaultMaterial()
    {
        Uint8 rgb[3] = { 255, 255, 255 };
        getDefaultMaterial(rgb);
    }