Why aren't pointers initialized with NULL by default?

Can someone please explain why pointers aren't initialized to NULL ?
Example:

  void test(){
     char *buf;
     if (!buf)
        // whatever
  }

The program wouldn't step inside the if because buf is not null.

I would like to know why, in what case do we need a variable with trash on, specially pointers addressing the trash on the memory?


We all realize that pointer (and other POD types) should be initialized.
The question then becomes 'who should initialize them'.

Well there are basically two methods:

  • The compiler initializes them.
  • The developer initializes them.
  • Let us assume that the compiler initialized any variable not explicitly initialized by the developer. Then we run into situations where initializing the variable was non trivial and the reason the developer did not do it at the declaration point was he/she needed to perform some operation and then assign.

    So now we have the situation that the compiler has added an extra instruction to the code that initializes the variable to NULL then later the developer code is added to do the correct initialization. Or under other conditions the variable is potentially never used. A lot of C++ developers would scream foul under both conditions at the cost of that extra instruction.

    It's not just about time. But also space. There are a lot of environments where both resources are at a premium and the developers do not want to give up either.

    BUT : You can simulate the effect of forcing initialization. Most compilers will warn you about uninitialized variables. So I always turn my warning level to the highest level possible. Then tell the compiler to treat all warnings as errors. Under these conditions most compilers will then generate an error for variables that are un-initialized but used and thus will prevent code from being generated.


    Quoting Bjarne Stroustrup in TC++PL (Special Edition p.22):

    A feature's implementation should not impose significant overheads on programs that do not require it.


    Because initialisation takes time. And in C++, the very first thing you should do with any variable is to explicitly initialise it:

    int * p = & some_int;
    

    or:

    int * p = 0;
    

    or:

    class A {
       public:
         A() : p( 0 ) {}  // initialise via constructor
       private:
         int * p;
    };
    
    链接地址: http://www.djcxy.com/p/84426.html

    上一篇: 来自不同开关柜的c ++访问变量

    下一篇: 为什么默认情况下不使用NULL初始化指针?