Arduino Promotion Behavior

I was pulling up an old project (A little Simon game which has apparently fallen off the ‘net when I moved my site- will have to repost) to use as a classroom demonstration, and discovered that sometime in the last couple years, the int->unsigned long promotion in Ardino/Processing broke/changed without comment.

The code uses using primitive nested counters and delays to generate sounds and control difficulty, which means rather large numbers (100-microsecond scale delays running for seconds) are being thrown about. To isolate the change, I wrote the following test:

int constint = 500;

void setup()
{
Serial.begin(9600);
}

void loop()
{
testpromote(constint);
testpromote2(constint);
delay(1000);
}

void testpromote(int input)
{
Serial.print("Multiplying:");
Serial.print(input);
Serial.println("*1000");
unsigned long result;
result=input*1000;
Serial.print("Result:");
Serial.println(result);
}

void testpromote2(int input)
{
Serial.print("Multiplying:");
Serial.print(input);
Serial.println("*1000L");
unsigned long result;
result=input*1000L;
Serial.print("Result:");
Serial.println(result);
}

Which generates this output:

Multiplying:500*1000
Result:4294943008
Multiplying:500*1000L
Result:500000

Note that ul=int*int produces something *distinctly wrong*, while ul=long*int produces a valid result. Easy to work around, but somewhat alarming.

This entry was posted in Computers, DIY, Electronics, General, Objects and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *