Seems pretty basic to me... is the expression evaluator limited to 16 bits? It sure appears that way.
I'm running WinXP and IDE 1.5.6r2. Target platform is a Mega, I have not tried 1.0.5 or any other target processors, I would expect there would be no difference. But, I've been wrong before!
#define declareBigNumber 100000
const unsigned long constBigNumber = 100000;
#define declareBigNumberExpression 1000*100
const unsigned long constBigNumberExpression = 1000 * 100;
void setup() {
Serial.begin(9600);
Serial.println(declareBigNumber,DEC); // prints 100000 * correct
Serial.println(constBigNumber,DEC); // prints 100000 * correct
Serial.println(declareBigNumberExpression,DEC); // prints -31072 * incorrect!!
Serial.println(constBigNumberExpression,DEC); // prints 4294936224 * incorrect!!
}
void loop() {
}
Thank you! Seems that at least one of the arguments has to be cast with the trailing UL. Does not appear to matter which one, although I would expect it makes the most sense to cast the first one like this:
The Arduino compiler defaults integers to 16 bit unless explicitly forced to a
wider type. The constant 100000 is not 16 bit so I'd never expect it to work.
Evaluating 1000 * 100 in a default context is going to use 16 bit multiply routine.
You can cast expressions so their results are wider:
((long) 1000) * 100
But the 1000L syntax is a handy shortcut. There is also U for unsigned,
so that 40000 (not 16 bit if signed) can be notated 40000U, casting it to
16 bit unsigned which can represent that value.
Technically, you shouldn't call type specifiers that appear after a numeric constant a cast. Rather, they are called data type suffixes and they are used to clarify the type of a numeric constant. You can read more about them at:
econjack:
Technically, you shouldn't call type specifiers that appear after a numeric constant a cast. Rather, they are called data type suffixes and they are used to clarify the type of a numeric constant. You can read more about them at:
avr_fred:
Seems pretty basic to me... is the expression evaluator limited to 16 bits? It sure appears that way.
I'm running WinXP and IDE 1.5.6r2. Target platform is a Mega, I have not tried 1.0.5 or any other target processors, I would expect there would be no difference. But, I've been wrong before!
Serial.println(declareBigNumber,DEC); // prints 100000 * correct won't compile on 1.0.5
Serial.println(constBigNumber,DEC); // prints 100000 * correct
Serial.println(declareBigNumberExpression,DEC); // prints -31072 * incorrect!!
Serial.println(constBigNumberExpression,DEC); // prints 4294936224 * incorrect!!
}
void loop() {
}
I would suggest to check with developers of IDE 1.5.6r2.
This code Serial.println(declareBigNumber,DEC); // prints 100000 * correct won't compile on 1.0.5
Would't expect it to compile, but what do I know.
Vaclav