MEGA 2560: Simple program - One analogWrite turns off the other I'm using Windows 10, Arduino 1.8.12 (Windows Store 1.8.33.0)

I have an Arduino MEGA 2560 and a red LED connected to pin 4.

#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  0);
  analogWrite(RED,  100);
}

void loop() {

}


This code lights up the red LED. 

However, when I write 1 to the GREEN pin analogWrite(GREEN,  1), the red LED goes off. I'm expecting the red LED to stay on.


#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  1);
  analogWrite(RED,  100);
}

void loop() {

}





The red LED stays on when both written values are the same, e.g.

  analogWrite(GREEN,  25);
  analogWrite(RED,  25);


I also found that adding some "garbage" code at the beginning fixes the issue. I wasn't able to get the garbage into a simpler form without both pins shutting off.


#define RED 4
#define GREEN 2

void setup() {
  // GARBAGE BEGIN ===
  unsigned long t = millis();
  const unsigned long period = 10;
  float progress = float(t % period)/period;
  float r = progress * 0;
  // GARBAGE END ===

  analogWrite(GREEN,  100 + r);
  analogWrite(RED,  50 + r);
}

void loop() {

}




Update: Thanks all for your comments. Setting the pinMode to output did not fix the issue. However, changing the function declaration to __attribute__((optimize("-O0"))) void setup() { fixed the issue. -O1 also works, but -O2 fails.
As you are using using ArduinoIDE >=1.8.10 its an "optimization" problem by the compiler for the Mega try to replace the line 

 void setup() 


with 

 void setup() __attribute__((optimize("-O0"))); 


// also -O1 works the default -Os and -O3,-O4 not

Actually the problem is not the IDE version but the included AVR boards package version.  You can install any AVR boards package in any IDE with Boards Manager. Last good AVR boards package is 1.6.21. If your compiler (tool chain) shows 7.03 in the output window you  are affected. I have examples where the compiler even optimizies the loop away, which ends in funny results - I dont know wether other boards are also affected but the MEGA is for sure.