Casting float to integer costing 800 bytes of program memory

Hi all,

Scratching my head with this one. Before I use this line

int alt = (int) af;

I have used 28390 bytes afterwards the sketch is too big at 29192. I am using a 32u4 Pro micro.

Anybody have any ideas?

Thanks

It's nearly impossible from such a small code snippet to determine what is going on at all.

If you are going to cast a float to an int do you really need the float in the first place ?

It is actually a double from a bmp280 pressure sensor initially which I have cast to float with a few bytes of program memory. The device I am sending it to only requires integers but I am bewildered by that one action taking so much memory. Here is the code leading to that.

char result = bmp.startMeasurment();
result = bmp.getTemperatureAndPressure(T, P);

double A = 44330.0 * (1 - pow(P / P0, 1 / 5.255));
A = A * 3.28084;
float af = (float) A;

Up to that point 28390 bytes used.
Add this.

int alt = (int) af;

and sketch is too big at 29192 bytes

It seems unlikely that the cast makes that much difference. I compiled two versions of the code, just making up some bogus values:

void setup() {
  Serial.begin(9600);
  
/*
    double P = 10.0;
    double P0 = 5.0;
    
    double A = 44330.0 * (1.0 - pow(P / P0, 1.0 / 5.255));
    A = A * 3.28084;
    float af = (float) A;
    Serial.println(af);
*/
    float P = 10.0;
    float P0 = 5.0;
    
    float af = (44330.0 * (1.0 - pow(P / P0, .190295))) * 3.28084;   // 1.0 / 5.255 = .190295
    Serial.println(af);
}

void loop() {
}

And both versions generate exactly the same flash and SRAM memory usage. BTW, the Arduino IDE does not support 64-bit floating point, so a double is actually coded as a float by the compiler.

Thanks for that, nice to know about the double as float. I tried adding some other code.

double q = 32767.32767; int z = (int) q;

no change in program space at all.

clemeilio: Thanks for that, nice to know about the double as float. I tried adding some other code.

double q = 32767.32767; int z = (int) q;

no change in program space at all.

if you don't do anything with the new variables, they will more then likely be optimised away by the compiler. Hence no difference in size.

There is a lot in what you have just said. The end result to the integer alt is split into LSB and MSB and stored in an array ready for an SPI read. if I remark out the store into an array all is well.

I am probably just running out of space.

Confirmed as running out of memory. Thanks to all for your help.

Also... Remember to be careful of RAM usage as well. May not be your current problem, but on a small processor, You can't wait until the compiler says you have used 100 or 1000 bytes, as each program is different, and the runtime consumes 'extra' memory for the stack and heap. On a larger program with temp variables flying around everywhere it's not unusual to leave 500b to a K or more for transient use.

Hah... beat me to it!