How to set a default value of float* argument which should be a pointer to array

Viewed 411

I'm trying to set a default value for float* (C++) as a function argument. For example -

Foo(float* x = (a default value should be {0,250}))

Does anyone know how to do this?

2 Answers

Since x is a pointer, you cannot set a default numeric value for it. You can only set a default address. To emulate giving it a default value, have a constant float (or in this case a float[2]) somewhere with that value and make x default to it instead.

const float default_x[2] = { 0.f, 250.f };

void foo(const float * x = default_x) {
    // use x
}

Beware that using c style arrays is error prone and not recommended in modern c++ code. Instead, prefer std::array when the size of known at compile time or std::vector otherwise. For example the following code would achieve a similar result and is safer to use :

#include <array>

const std::array<float, 2> default_x = { 0.f, 250.f };

void foo(const std::array<float, 2> & x = default_x) {
    // use x
}

This sort of thing is often better done through function overloading.

void f(float* arg) {
    // whatever
}

void f() {
    static float default_data[] = { 0, 250 };
    f(default_data);
}
Related