-3

I'm working on a project in which I need to set all global variables to value 1 instead of 0. Kindly explain how I can do this.

MCU - STM32 ARM microcontroller
Language - C/C++

It's possible by initially assigning the value 1 but I want to know of any alternative way to do this.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 4
    C or C++? Pick one. In C++ you could make a class with a constructor, and use it for your own variables. – HolyBlackCat Sep 03 '23 at 05:09
  • 1
    There is no such language as "C/C++". – paddy Sep 03 '23 at 05:10
  • You seem to want to change what the *default initialization* rule is, and that would be like wanting to change the Standard-specified rules of the language. – Adrian Mole Sep 03 '23 at 05:24
  • You could use explicit initialization for each variable but, rather than specifying a literal constant, use a macro/alias and change that (once, globally) if/when you want to use a different initial value. – Adrian Mole Sep 03 '23 at 05:25

1 Answers1

2

As others said in the comments, this is a bad idea, as it goes against the C and C++ standards.

It is also very complicated to accomplish, and @old_timer said, requires to change the compiler itself. The reason for that is this:

In most translation environments (of which compiler is part of) the initial zeroing of global and static variables which are not initialized explicitly, is not performed by code generated by compiler, that would be too lengthy. Instead, the compiler allocates all such variables together into one continguous section (traditionally called .bss or COMMON); and then the linker attaches a small piece of code (called startup code) which (among other things) simply fills all this section by zero bytes. This works, as all zero variables - including multi-byte ones, e.g. 16-bit or 32-bit variables - consists of all zero bytes.

Simply replacing the startup code to fill the .bss section by ones would not work, as the information of width of individual variables in that section is already lost at this point. So, for example, a 32-bit variable would end up being initialized to 0x01010101, which is not what you want.

As it's only the compiler which "knows" the width of individual variables, you would need to modify the compiler itself to perform the initialization. You could do that only with open-source compilers, and it's an unreasonably complex thing to do.

In short, the answer is: just don't.

wek
  • 137
  • 3