【问题标题】:Default values for integers in structure结构中整数的默认值
【发布时间】:2011-09-27 13:18:28
【问题描述】:

我不知道如何为结构中的整数设置默认值。例如

 typedef struct {
        char breed[40];
        char coatColor[40];
        int maxAge = 20;
    } Cat;

上面的代码在执行时给了我一个错误 - 预期的';'在声明列表的末尾

【问题讨论】:

标签: c


【解决方案1】:

你不能在 C 中指定默认值。你可能想要的是一个“init”风格的函数,你的结构的用户应该首先调用它:

struct Cat c;
Cat_init(&c);

// etc.

【讨论】:

    【解决方案2】:

    在 C 中,您不能在结构中给出默认值。这种语法根本不存在。

    【讨论】:

      【解决方案3】:

      简而言之,你不能。它根本不是 C 的一个特性。

      【讨论】:

        【解决方案4】:

        结构是一种类型。类型(所有类型)没有默认值。

        // THIS DOES NOT WORK
        typedef char = 'R' chardefault;
        chardefault ch; // ch contains 'R'?
        

        你可以在初始化时给对象赋值

        char ch = 'R'; // OK
        struct whatever obj = {0}; // assign `0` (of the correct type) to all members of struct whatever, recursively if needed
        

        【讨论】:

          【解决方案5】:

          你可以初始化,但字符串不实用(最好使用你的自定义函数)

          typedef struct {
                  char breed[40];
                  char coatColor[40];
                  int maxAge; 
          } Cat;
          
          Cat c = {"here39characters40404040404044040404040",
                   "here39characters40404040404044040404040",
                    19
          };
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-02-24
            • 2010-10-19
            • 2014-01-17
            • 2010-12-23
            • 1970-01-01
            • 2016-09-19
            • 1970-01-01
            • 2012-11-22
            相关资源
            最近更新 更多