让编译器检查数组初始化程序的数量 [英] Have compiler check the number of array initializers

查看:75
本文介绍了让编译器检查数组初始化程序的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用少于元素数量的初始化程序初始化数组(在C ++中,但是任何适用于C的解决方案也可能在这里工作)完全合法:

Initializing an array (in C++, but any solution which works for C will likely work here as well) with less initializers than it has elements is perfectly legal:

int array[10] = { 1, 2, 3 };

但是,这可能是晦涩的bug的来源。有没有办法让编译器(gcc)检查一个特定数组的初始化程序数量,并在声明且实际大小不匹配时发出警告甚至错误?

However, this can be a source of obscure bugs. Is there a way to have the compiler (gcc) check the number of initializers for one specific array, and emit a warning or even an error if declared and actual size don't match?

我知道我可以使用 int array [] = {1,2,3}; 然后可以使用涉及 sizeof(数组)来验证我的期望。但是我在其他翻译单元中使用了 array ,因此我必须用一个明确的大小声明它。因此,这个技巧对我不起作用。

I know I can use int array[] = { 1, 2, 3 }; and could then use static assertions involving sizeof(array) to verify my expectation there. But I'm using array in other translation units, so I have to declare it with an explicit size. So this trick won't work for me.

推荐答案

(根据要求从评论中推荐)

(promoted from a comment as requested)

如果数组中的值对于系统的正确功能很重要,并且结尾处的零初始化值会导致错误,那么我将添加一个单元测试以验证数组包含正确的数据,而不是尝试在代码中强制执行。

If the values in the array are important to the correct functionality of the system, and having zero-initialized values at the end causes bugs, then I would just add a unit test to verify the array contains the right data, instead of trying to enforce it in the code.

这篇关于让编译器检查数组初始化程序的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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