开发者

Default values for integers in structure

I can't figure out how to set default value for integer in structure. For example

 typedef struct {
        char breed[40];
        char coatColor[40];
        int maxAg开发者_运维问答e = 20;
    } Cat;

The code above gives me an error on execution - Expected ';' at end of declaration list


You cannot specify default values in C. What you probably want is an 'init' style function which users of your struct should call first:

struct Cat c;
Cat_init(&c);

// etc.


In C you cannot give default values in a structure. This syntax just doesn't exist.


Succinctly, you can't. It simply isn't a feature of C.


A structure is a type. Types (all types) do not have default values.

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

You can assign values to objects in initialization

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


you can initialize but it's not practical with strings ( better to use your custom functions)

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

Cat c = {"here39characters40404040404044040404040",
         "here39characters40404040404044040404040",
          19
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜