Global - Local variable

Dear Community,

I have a little question about local and global variables. When I start this code:

int currenttime;
double x;

uint16_t table{1,2,3,4,5,6,7,8,9,10};

void setup() {
// put your setup code here, to run once:
Serial.begin(250000);
}

void loop() {
// put your main code here, to run repeatedly:
currenttime = micros();
for(int i=0; i<10; i++)
{

x = 765.98 * table*;*

  • }*

  • Serial.println(micros() - currenttime);*
    }
    [/quote]
    my Arduino Due needs 25µs. The variable ‘x’ is global. When I declare the variable x in the loop it needs just 1µs. Where is my mistake? I need to declare x as a global variable to use it in the pid function, and want to get this code as fast as possible.
    Many thanks in advance.
    Dave
    p.s.: I don’t know why, but in the calculation behind the ‘table’ variable is the i in the square bracket missing.

Where is my mistake?

It is in assuming that the code does the same thing when x is local as when it is global.

When x is global, the result of the operations in the for loop might be used elsewhere. When x is local, the compiler can see that the result of the operations in the for loop is not used anywhere else, and removes the entire for loop.

If you print x after the for loop, when x is local and when it is global, you will see identical times.

That's it... Thanks a lot.

Dave