Pages: [1]   Go Down
Author Topic: Strange array index in Print::printNumber  (Read 575 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Edison Member
*
Karma: 64
Posts: 1638
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Why is the array index for 'buf' in Print::printNumber an unsigned long?

I change
Code:
 unsigned long i = 0;

To
Code:
 uint8_t i = 0;
And it seems to work and saves about 60 byte.
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 616
Posts: 49444
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

What happens, with your modification, if the array being printed contains 300 characters?
Logged

0
Offline Offline
Edison Member
*
Karma: 64
Posts: 1638
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Can't happen since buf has dimension 32.  
Code:
 unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars.
This is the max number of characters required to print an unsigned long in binary/ base 2.

The while loop in printNumber limits i to 32 or less.
Logged

Cape Town, South Africa
Offline Offline
Full Member
***
Karma: 0
Posts: 177
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

If that is only a local variable, the optimizer normally does a good job of 'squashing' it (with int normally).  Maybe it sucks for unsigned long smiley
Logged

0
Offline Offline
Edison Member
*
Karma: 64
Posts: 1638
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I would have expected it to optimize also but it doesn't.  My guess was that the while loop fools the compiler since that is what limits the size of i but who knows.

Anyhow unsigned long makes Print about 60 bytes larger.

Actually the compiler can't optimize because there is sort of a bug in Print.  If you call print with base == 1 it will zero most of memory.  If you change the unsigned long to uint8_t it will not behave the same.  It will loop zeroing 256 bytes of memory.
« Last Edit: June 25, 2010, 09:02:39 pm by fat16lib » Logged

Pages: [1]   Go Up
Jump to: