am working with and Arduino nano and according to this, I can append strings to numbers by doing: stringThree = stringOne + 123; but when I do:

sensorValue = analogRead(A0);
String x1 = "{\"Volt\":"+sensorValue;

I get this unwanted output!


but doing this it works fine.

sensorValue = analogRead(A0);
String x1 = "{\"Volt\":";
x1 += sensorValue;




In the first example you are adding an integer to the address of a string literal and then converting it to a String.

In the second example you are converting a string literal to a String and then appending an integer.

The key point here is string literal. The compiler just sees it as an address in flash memory. It's down to the functions you use with that address that define it as a string. So when you add an integer to it you are just adding an integer to the address, which of course changes the address. So then when you go to convert whatever is at that address to a String you end up with garbage.

  • Pretty nice explanation... it must be maybe some kind of pointer operation behind the scenes... – ΦXocę 웃 Пepeúpa ツ Feb 7 '17 at 12:10
  • 1
    That is precisely what it is. In C there is no such thing as a "string", only a pointer to some memory location. It's only when you use that pointer that the contents are interpreted as a "string". – Majenko Feb 7 '17 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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