Hydra Hydra - 2 months ago 8
C++ Question

Initialization of const char array as argument of an overloaded function

This will compile but it is certainly not correct, I've got strange outputs.
I would be glad if someone can tell me the correct way.

void test(const char c[]={'\0'}); //It will compile but strange outputs
//void test(const char c[]={'x','\0'}); //compile error

void loop() {
const char c[] = {'u','h','u','\0'};

test();
test(c);
}

void test(const char c[]){
Serial.println(c);
}

Answer

The default initialization to zero is probably not what you want. You are actually pointing the default to NULL instead of an empty string because const char c[] and const char *c in a function parameter is basically the same thing.

You can do

void test(const char c[]=""); 

instead.

I'm assuming that you are using a C++ compiler and I would recommend that you tag the question as C++ as C does not have default parameters or polymorphism.