pb with simple led blinking code

hello all
who can help me, here after 2 similar codes, I just add or not a Serialprint, and the led blinks, or does not blink. I do not understand, thank you very much
Pat from Toulouse (France)

// arduino code 1
// blinking led OK (with a Serial_print included in the delay loop to read counter value)
unsigned int counter, toggle=0;
void setup()
{ pinMode (13, OUTPUT);
Serial.begin(115200);
// timer 2 configured at 16uS
cli(); // Unactivation of the globale interruption
bitClear (TCCR2A, WGM20); // WGM20 = 0
bitClear (TCCR2A, WGM21); // WGM21 = 0
TCCR2B = 0b00000110; // Clock / 256 soit 16 uS et WGM22 = 0
TIMSK2 = 0b00000001; // Locale interruption autorised by TOIE0
sei(); // Activation of the globale interruption
}
void loop()
{ start:
if (toggle==0){digitalWrite(LED_BUILTIN,0);
toggle=1-toggle;}
else {digitalWrite(LED_BUILTIN,1);
toggle=1-toggle;}

counter=0;
delay_1s:
if (counter < 1000){
// Serial.print(counter);
goto delay_1s;}
goto start;}

ISR(TIMER2_OVF_vect)
{ TCNT2 = 256 - 62; // 62 x 16 µS ~ 1ms
counter++;}

// arduino code 2
// blinking led KO (without Serial_print included in the delay loop !!!)
unsigned int counter, toggle=0;
void setup()
{ pinMode (13, OUTPUT);
Serial.begin(115200);
// timer 2 configured at 16uS
cli(); // Unactivation of the globale interruption
bitClear (TCCR2A, WGM20); // WGM20 = 0
bitClear (TCCR2A, WGM21); // WGM21 = 0
TCCR2B = 0b00000110; // Clock / 256 soit 16 uS et WGM22 = 0
TIMSK2 = 0b00000001; // Locale interruption autorised by TOIE0
sei(); // Activation of the globale interruption
}
void loop()
{ start:
if (toggle==0){digitalWrite(LED_BUILTIN,0);
toggle=1-toggle;}
else {digitalWrite(LED_BUILTIN,1);
toggle=1-toggle;}

counter=0;
delay_1s:
if (counter < 1000){
// Serial.print(counter);
goto delay_1s;}
goto start;}

ISR(TIMER2_OVF_vect)
{ TCNT2 = 256 - 62; // 62 x 16 µS ~ 1ms
counter++;}

Use CTRL T to format the sketch.

Please use code tags.
Use the </> icon in the posting menu.

[code] Paste sketch here. [/code]

thank you for youtr 2 answers DeltaG.
I will supress the "goto start" as not useful, and will use "while" for the loop.
It is just strange that the compiler do not consider also an infinite loop when I add a serialPrint...

poms63:
thank you for youtr 2 answers DeltaG.
I will supress the "goto start" as not useful, and will use "while" for the loop.
It is just strange that the compiler do not consider also an infinite loop when I add a serialPrint...

When you add a Serial.print() inside the loop, the compiler has to check the value of counter each time, because it doesn't know if the Serial.print() function changes its value. Without Serial.print(), the compiler "knows" that counter cannot change inside the loop, so it can assumes it's always 0 (the compiler doesn't "know" that ISRs can change variables).

Adding volatile to counter's definition, as Delta_G mentioned, tells the compiler that counter can change at any time.