Can't clear MCUSR before setup()

One of my Pro Mini (8MHz, 3V3) based LoRaWAN nodes malfunctioned a few days ago causing it to transmit every one or two seconds for a few hours. This, of course, not only breached The Things Network’s fair use policy but drove a bulldozer through it! The problem was caused by a brown-out reset loop.

To prevent my nodes from BORFing again I am reprogramming them to enter into zombie mode when the brown-out reset flag is set in the MCUSR register of the microcontroller. But during experimentation I came accross a weird (for me) behaviour. As stated in the datasheet, it is good practice to clear the MCUSR register as soon as possible after startup/reset. If I place the “MCUSR = 0” statement outside of setup() it does not compile (" expected unqualified-id before ‘volatile’ "). But if I place the statement inside setup(), then all is good!

It is not a big deal, but I would like to know why this happens - is it a feature or a bug?

byte mcusr = MCUSR;

MCUSR = 0; //<-------- This does not compile

void setup() {
  //MCUSR = 0; //<------- This does compile
  int porf = bitRead(mcusr, PORF);
  int extrf = bitRead(mcusr, EXTRF);
  int borf = bitRead(mcusr, BORF);
  int wdrf = bitRead(mcusr, WDRF);
  
  Serial.begin(9600);
  
  Serial.println();
  Serial.print("PORF: ");
  Serial.println(porf);
  Serial.print("EXTRF: ");
  Serial.println(extrf);
  Serial.print("BORF: ");
  Serial.println(borf);
  Serial.print("WDRF: ");
  Serial.println(wdrf);
  
}

void loop() {
  // put your main code here, to run repeatedly:

}

NB Some bootloaders clears MCUSR before the application is run. For example, the above code does not really work on my ancient UNO.

My guess is you can't change a CPU register before your program is started. You can define a global variable outside of "main" but MCUSR is not a variable but rather a register, thus, your program must be running (or entered "main")

Most code must be inside a function. Variable initialization may be outside a function but must be combined with variable type declaration.

The constructors for global-scope class instances run before setup(). So, how about:

class McusrReseter {
  public:
    McusrReseter() {
      MCUSR = 0;
    }
};

McusrReseter reseter;

void setup() {
}

void loop() {
}

Thank you all! I am a C++ novice and I have learned something today!