#多么痛的领悟# 关于数组中的元素默认初始值

来源:互联网 发布:3d美工 编辑:程序博客网 时间:2024/05/20 09:22

C++规定,数组在函数内外初始化值是不同的,即使是main()函数也不例外,比如我们没有初始化一个int数组,如果在函数外面定义,那么int数组中的元素全为0.如果在函数里面的定义的话(包括main()函数)那int数组中的元素值 是不确定的。

这是一个惨痛的教训,可能在有的编译器中,在main()函数中定义的数组元素被默认初始化为0.但某些编译器中就不是,至少POJ用的编译器就不是,导致我WA好多次,说多了都是眼泪。下面这段话是C++primer中的解释。


If we do not supply element initializers, then the elements are initialized in the same way that variables are initialized 

  • Elements of an array of built-in type defined outside the body of a function are initialized to zero.
  • Elements of an array of built-in type defined inside the body of a function are uninitialized.
  • Regardless of where the array is defined, if it holds elements of a class type, then the elements are initialized by the default constructor for that class if it has one. If the class does not have a default constructor, then the elements must be explicitly initialized.
原创粉丝点击