c++ - Why are global and static variables initialized to their default values? -


in c/c++, why globals , static variables initialized default values?

why not leave garbage values? there special reasons this?

  1. security: leaving memory alone leak information other processes or kernel.

  2. efficiency: values useless until initialized something, , it's more efficient 0 them in block unrolled loops. os can 0 freelist pages when system otherwise idle, rather when client or user waiting program start.

  3. reproducibility: leaving values alone make program behavior non-repeatable, making bugs hard find.

  4. elegance: it's cleaner if programs can start 0 without having clutter code default initializers.

one might wonder why auto storage class does start garbage. answer two-fold:

  1. it doesn't, in sense. first stack frame page @ each level (i.e., every new page added stack) receive 0 values. "garbage", or "uninitialized" values subsequent function instances @ same stack level see previous values left other method instances of own program , library.

  2. there might quadratic (or whatever) runtime performance penalty associated initializing auto (function locals) anything. function might not use or of large array, say, on given call, , invoked thousands or millions of times. initialization of statics , globals, otoh, needs happen once.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -