1

I want to print a string together with number. My code is

Serial.println("Test " + index++);

(In setup() I initialized variable index to 0.) In Java it would output

Test 0
Test 1
Test 2
Test 3
...

But I get this output instead:

Test
est
st 
t

Can anybody explain it to me please?

2 Answers 2

6

Serial.println() prints the value of one expression. The expression you passed it was `("Test " + index++).

In C/C++ a character literal such as "Test " evaluates to the memory address its first character. Adding 1 to that address gives the address of the next (or 2nd) character. Adding 2 to it gives the address of the 3rd character, and so on.

To get what you were expecting, the value of the literal, AND the value of the index, you would write:

Serial.print("Test ");
Serial.println(index++);

If you had created a String variable with the value "Test ", then the String expression, ("Test " + index++) would have been evaluated differently: The "+" operator would have concatenated the String "Text ", with the String equivalent of the current value of "index"; but that isn't the way a character literal is treated. There is a C++ String library among the Arduino libraries but it's use is not recommended because Strings get reallocated and copied when they get concatenated, resulting in excessive memory use, and the Arduino has very little memory.

2

JRobert explains very well why it does not work.

Instead of the Serial.print you also can use the sprintf function in case you need a more complicated string to build, or in case you want to mix two different types in one line:

char str[100];
int index = 0;
sprintf(str, "Test %d", index++);
Serial.println(str);

Make sure the buffer (100) is big enough to store the full string including the end symbol ('\0').

For safety you also can use:

snprintf(str, 100, "Test %d", index++);

This will make sure max. 100 characters are filled in (and the remainder is clipped).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.