Reputation: 122392
I am programming in Arduino 022 for the Arduino Mini Pro. I have the following function:
String join(const String str, ...) {
Serial.println("join");
va_list args;
va_start(args, str);
Serial.println("result init");
String result = "";
for (String strArg = str; strArg != NULL; strArg = va_arg(args, String)) {
Serial.println(result);
result += strArg + ARG_DELIMITER;
}
result = result.substring(0, result.length() - 1);
Serial.println("join end");
return result;
}
When I call this function, the program halts, and the built in LED in pin 13 turns on. "join" is never printed to the serial monitor. Are variadic functions not permitted on Arduino?
Upvotes: 1
Views: 2367
Reputation:
When you call the code, does it look like:
join( "foo", "bar", NULL ); // ok
or:
join( "foo", "bar" ); // wrong
You have to provide the NULL terminator yourself - the compiler won't do it.
Edit: This assumes that String is a typedef for char * (because you compare it with NULL), but if it is there is much else wrong with your code. Please clarify what the type of String is.
Upvotes: 1
Reputation: 18964
You can't pass most class types to a variadic function - only POD types (5.2.2 para 7 in the standard); if you do the behaviour is undefined - which could cause the problems you're getting. I'm pretty sure the Arduino String class is not a POD, so this isn't going to work.
You might be better off using char arrays (at least in some places), eg
String join(char const * const str, ...)
if this doesn't cause too much ugliness at the call site, or perhaps just provide overloads for 1 to N Strings.
Also - can a String object ever be equal to NULL? Your test for strArg != NULL
looks dubious.
Upvotes: 2