Dev Kanchen Dev Kanchen - 1 year ago 83
C++ Question

Default values for array arguments

Just playing around a little with C++. What I really want to do is to be able to setup a function with default values defined for an array or pointer argument. To keep things simple, let's just use an array. Like so:

void experimentA(char a[3] = {'a', 'b', 'c'});

The compiler (LLVM GCC 4.2 with GNU99) complains "Expected expression". That is quite obtuse, but I was told by colleagues that this is happening because the 'value' I'm trying to assign is statically allocated, whereas the variable I'm trying to assign it to (
) is auto.

But I'm not completely sure if that's the case, since I'm able to do this:

void experimentB(char a[3] = "abc");

And the compiler merely warns me that string-literal to char* conversion is deprecated.

I don't understand how "abc" differs fundamentally from {'a','b','c'} in order to cause this discrepancy. Any insight is much appreciated!

Answer Source

Your colleagues are wrong or maybe you misunderstood.

The first clue to understanding is that you cannot have an array as a function parameter in C or C++. The reasons are historical. So when you write void experimentA(char a[3] ...) the compiler automatically converts it to a pointer, i.e. void experimentA(char* a ...). So the real question is why "abc" is a suitable default value for a and { 'a', 'b', 'c' } is not. The reason is as the compiler explains, "abc" is an expression and { 'a', 'b', 'c' } is not (its an initialiser). There are some places in C++ where you can use an initialiser and some where you can't. Default value for a parameter just happens to be one of the places you can't.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download