Hi there!
I'm sorry to say I'm painfully new to all this arduino stuff and coding in general to be honest. Can anyone please explain these results to me? I'm pulling my hair out here!
I've seen something like this before. Not on the Arduino (because I haven't tried it). It was years ago on PDPs, and the explanation has to do with the storage for floating point numbers. If you want to get into the depths of it, try reading up on hidden bit normalized. I haven't read the pertinent tech docs, so I don't know for a fact that the Atmel uses that, but it is an IEEE standard for floating point storage in binary. I'm not even going to claim, for sure, that this is the cause here, but it sure sounds like a good candidate.
I can only speculate that it works in the OP's example #2 because the parser is treating the numeric constants as floats, i.e. "2.0", "4.0". But I could be way off base there too.
If you only need integer powers of two, you don't need to use "pow" at all.
An appropriately-sized variable and a shift operation are all that are needed.
e.g.
This has come up fairly recently and both your issues were addressed. The too small by one issue was caused by the pow function's use of floats so pow(2,2) gives 3.999 or similar, which when you cast it to int is 3. Add 0.5 before you cast to int.
The reason the explicit evaluations outside the loop work better is because the compiler can see that they are constants and evaluates them at compile time using its own pow calculation. As you can see, it does a better job.
Yeah, cheers! A bit of further digging and as was kindly pointed out I found some nice information in some other posts on this forum. In my defense I did have a look before I posted initially, but must've just missed this wonderful post http://arduino.cc/forum/index.php/topic,60701.0.html.