Pages: [1]   Go Down
Author Topic: Bug : String concatenation garbage output.  (Read 1026 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 3
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Test Envrionment :
Windows 7 x64 Arduino Mega
Ubuntu 9.10 Arduino Mega

Test Code
Code:
void setup()
{
Serial.begin(9600);
delay(1000);
Serial.println("Should print fine.");
int tmp = 13;
Serial.println("Printing 13 " + tmp);
Serial.println("Printed.");
}
void loop()
{
  
}
}

The output for "printing 13" does not arrive at all and the text "Printed." comes back twice.

Logged

SF Bay Area (USA)
Offline Offline
Tesla Member
***
Karma: 137
Posts: 6806
Strongly opinionated, but not official!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

"+" does not perform string concatenation, or conversion of integers to strings, in the arduino Language(s) (C, C++)
Logged

Netherlands
Offline Offline
Jr. Member
**
Karma: 0
Posts: 83
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

LolrusPL, if you're looking for a way to correct your code, have a look at this:

Code:
   int tmp = 13;
    char str[12 + 2 + 1]; // 12 for string, 2 for tmp, 1 for \0
    snprintf(str, sizeof(str), "Printing 13 %d", tmp);
    Serial.println(str);
Logged

UK
Offline Offline
Faraday Member
**
Karma: 17
Posts: 2884
Gorm deficient
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
and the text "Printed." comes back twice.

The compiler probably put the strings, "Printing 13 " and "Printed." in consecutive locations in memory.
The first string occupies 13 bytes of memory (including the terminating null character)
Adding 13 to the address of the first string gives you the address of the second.

That's why "Printed." got printed twice.

HTH
Logged

Per Arduino ad Astra

Pages: [1]   Go Up
Jump to: