在C/C ++中初始化数组是否是一种好习惯? [英] Is it good practice to initialize array in C/C++?

查看:92
本文介绍了在C/C ++中初始化数组是否是一种好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到一种情况,我需要比较两个文件(黄金文件和预期文件)以验证测试结果,即使写入两个文件的数据相同,但文件也不匹配.

在进一步研究中,我发现有一个结构,其中包含一些整数和一个由64个字节组成的char数组,并且在大多数情况下并没有使用char数组的所有字节,并且该数组中的未使用字段包含随机数据,这就是导致不匹配的原因.

这给我带来了一个问题,即是否也像在Java中那样,在C/C ++中初始化数组也是一种好习惯?

解决方案

在使用内存/变量之前初始化内存/变量是一种好习惯-未初始化的变量是大量bug的来源,通常很难跟踪. >

初始化所有数据时,将其写入文件格式是一个很好的主意:它使文件内容更整洁,使它们更易于使用,如果有人错误地尝试使用"未初始化的数据,则不容易出现问题(请记住,将来读取数据的可能不只是您自己的代码),并使文件更具可压缩性.

在使用变量之前不对其进行初始化的唯一很好的理由是在性能关键的情况下,在技术上初始化是不必要的",并且会产生大量开销.但是在大多数情况下,初始化变量不会造成重大危害(特别是如果仅在使用变量之前就声明它们),但是通过消除常见的bug来源,可以节省大量开发时间.

I recently encountered a case where I need to compare two files (golden and expected) for verification of test results and even though the data written to both the files were same, the files does not match.

On further investigation, I found that there is a structure which contains some integers and a char array of 64 bytes, and not all the bytes of char array were getting used in most of the cases and unused fields from the array contain random data and that was causing the mismatch.

This brought me ask the question whether it is good practice to initialize the array in C/C++ as well, as it is done in Java?

解决方案

It is good practice to initialise memory/variables before you use them - uninitialised variables are a big source of bugs that are often very hard to track down.

Initialising all the data is a very good idea when writing it to a file format: It keeps the file contents cleaner so they are easier to work with, less prone to problems if someone incorrectly tries to "use" the uninitialised data (remember it may not just be your own code that reads the data in future), and makes the files much more compressible.

The only good reason not to initialise variables before you use them is in performance-critical situations, where the initialisation is technically "unnecessary" and incurs a significant overhead. But in most cases initialising variables won't cause significant harm (especially if they are only declared immediately before they are used), but will save you a lot of development time by eliminating a common source of bugs.

这篇关于在C/C ++中初始化数组是否是一种好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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