Why separate variable definition and initialization in C++?

前端 未结 8 1531
心在旅途
心在旅途 2021-02-18 15:22

I\'m currently working on some quite old C++ code and often find things like

int i;
i = 42;

or

Object* someObject = NULL;
someO         


        
8条回答
  •  时光取名叫无心
    2021-02-18 15:58

    There is a good technical reason on ROM-based hardware, it is NOT a style issue:

    On ROM/EEPROM based embedded systems, this has an effect on where in the binary the value is written. Uninitialized variables are written into .bss, whereas initialized variables are written into .data. Premature initialization will bloat your ROM space, which on older embedded systems can get you into big, big trouble. If you are running on a system with a small ROM, you can run out of memory if you initialize needlessly. Some goofy compilers will even address directly into the ROM, making these values effectively read-only if you are not careful.

    e.g. See this GameBoy example for a more thorough explanation: http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_varinit

提交回复
热议问题