为什么不用NULL初始化指针? [英] Why aren't pointers initialized with NULL by default?

查看:120
本文介绍了为什么不用NULL初始化指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这已经回答了,但我只是在这里或谷歌找不到答案,但我认为这是因为我不能键入正确的问题...



有人可以解释为什么不将指针初始化为NULL?

示例:

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

如果 buf 不为空,程序不会进入。



我想知道为什么,在什么情况下,我们需要一个带有垃圾桶的变量,特别是指向内存上的垃圾桶的指针?

解决方案

指针(和其他POD类型)应该被初始化。

然后问题变成谁应该初始化它们。






  • 编译器初始化它们。


  • 让我们假设编译器未初始化任何变量由开发人员初始化。然后我们遇到了初始化变量的情况,而开发人员在声明点没有这样做的原因是他/她需要执行一些操作然后赋值。



    所以现在我们有这样的情况,编译器添加了一个额外的指令给代码,初始化变量为NULL,然后稍后添加开发人员代码来做正确的初始化。或者在其他条件下,变量可能永远不会使用。很多C ++开发人员在这两个条件下都会以额外的指令为代价来哄骗。



    这不只是时间。但也空间。



    但是:您可以模拟强制初始化的效果。大多数编译器将警告您有关未初始化的变量。所以我总是把我的警告水平,尽可能最高的水平。然后告诉编译器将所有警告视为错误。在这些条件下,大多数编译器会为未使用和使用的变量产生一个错误,从而阻止生成代码。


    I guess this have been answered before, but I just couldn't find the answer here or on Google, but I think that it is because I couldn't type the right question...

    Can someone please explain why aren't pointers 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 to 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 unused and used and thus will prevent code from being generated.

    这篇关于为什么不用NULL初始化指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆