【问题标题】:C (or C++?) Syntax: STRUCTTYPE varname = {0};C(或 C++?)语法:STRUCTTYPE varname = {0};
【发布时间】:2011-02-03 23:23:15
【问题描述】:

通常人们会在堆栈上声明/分配一个结构:

STRUCTTYPE varname;

这个语法在 C 中是什么意思(或者这个只是 C++,或者可能特定于 VC++)?

STRUCTTYPE varname = {0};

其中 STRUCTTYPE 是结构类型的名称,例如 RECT 或其他东西。这段代码可以编译,它似乎只是将结构的所有字节归零,但我想确定是否有人有参考。另外,这个结构有名字吗?

【问题讨论】:

标签: c++ c syntax


【解决方案1】:

这是聚合初始化,是有效的 C 和有效的 C++。

C++ 还允许您省略所有初始化程序(例如零),但是对于这两种语言,没有初始化程序的对象是值初始化或零初始化的:

// C++ code:
struct A {
  int n;
  std::string s;
  double f;
};

A a = {};  // This is the same as = {0, std::string(), 0.0}; with the
// caveat that the default constructor is used instead of a temporary
// then copy construction.

// C does not have constructors, of course, and zero-initializes for
// any unspecified initializer.  (Zero-initialization and value-
// initialization are identical in C++ for types with trivial ctors.)

【讨论】:

  • C 不会对 std::string 进行零初始化,因为您在 C 中不会有 std::string。但除了挑剔之外,这是正确的。
  • +1,我不知道你可以把大括号留空。多么方便!
【解决方案2】:

在 C 中,初始化器 {0} 对于将 any 类型的 any 变量初始化为全零值是有效的。在 C99 中,这还允许您使用复合文字语法分配“零”给任何类型的任何可修改左值:

type foo;
/* ... */
foo = (type){0};

不幸的是,如果类型是基本类型(例如int x = {0};)或嵌套​​结构/数组类型(例如struct { int i[2]; } x = {0};),一些编译器会警告您在初始化器周围有“错误数量”的大括号。我会认为此类警告有害并将其关闭。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2018-09-26
    • 2017-04-27
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多