【发布时间】:2011-09-27 13:18:28
【问题描述】:
我不知道如何为结构中的整数设置默认值。例如
typedef struct {
char breed[40];
char coatColor[40];
int maxAge = 20;
} Cat;
上面的代码在执行时给了我一个错误 - 预期的';'在声明列表的末尾
【问题讨论】:
标签: c
我不知道如何为结构中的整数设置默认值。例如
typedef struct {
char breed[40];
char coatColor[40];
int maxAge = 20;
} Cat;
上面的代码在执行时给了我一个错误 - 预期的';'在声明列表的末尾
【问题讨论】:
标签: c
你不能在 C 中指定默认值。你可能想要的是一个“init”风格的函数,你的结构的用户应该首先调用它:
struct Cat c;
Cat_init(&c);
// etc.
【讨论】:
在 C 中,您不能在结构中给出默认值。这种语法根本不存在。
【讨论】:
简而言之,你不能。它根本不是 C 的一个特性。
【讨论】:
结构是一种类型。类型(所有类型)没有默认值。
// 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
【讨论】:
你可以初始化,但字符串不实用(最好使用你的自定义函数)
typedef struct {
char breed[40];
char coatColor[40];
int maxAge;
} Cat;
Cat c = {"here39characters40404040404044040404040",
"here39characters40404040404044040404040",
19
};
【讨论】: