C ++数组初始化 [英] C++ array initialization

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

问题描述

是将数组初始化为所有0的形式

is this form of intializing an array to all 0s

char myarray [ARRAY_SIZE] = {0} 支持所有编译器? ,

char myarray[ARRAY_SIZE] = {0} supported by all compilers? ,

如果是这样,其他类型的语法是否类似?例如

if so, is there similar syntax to other types? for example

bool myBoolArray[ARRAY_SIZE] = {false}


推荐答案

是的,这种初始化形式是由所有C ++编译器支持的。它是C ++语言的一部分。事实上,这是一个从C语言到C ++的习语。在C语言 = {0} 是惯用的通用零初始化器 。这也是在C ++中的情况。

Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++.

由于此initalizer是通用的, bool array你真的不需要一个不同的语法。 0 也用作 bool 类型的初始化程序,因此

Since this initalizer is universal, for bool array you don't really need a different "syntax". 0 works as an initializer for bool type as well, so

bool myBoolArray[ARRAY_SIZE] = { 0 };

保证用 false 。以及

char* myPtrArray[ARRAY_SIZE] = { 0 };

确保使用类型 char *的空指针初始化整个数组。

如果您认为它提高了可读性,您一定可以使用

If you believe it improves readability, you can certainly use

bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };

但关键是 = {0} 相同的结果。

但是,在C ++ = {0} 可能不适用于所有类型,例如枚举类型,它不能用积分 0 初始化。因此,C ++支持更短的形式

However, in C++ = { 0 } might not work for all types, like enum types, for example, which cannot be initialized with integral 0. Specifically for this reason, C++ supports the shorter form

T myArray[ARRAY_SIZE] = {};

只是一个空对 {} 。这将默认初始化任何类型的数组(假设元素允许默认初始化),这意味着对于基本(标量)类型,整个数组将被正确地初始化。

i.e. just an empty pair of {}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.

这篇关于C ++数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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