c struct with default valuabel?
Here I have the following struct
typedef struct d {
unsigned in开发者_C百科t size: 20;
} D;
the question is how the default variable size
be 10
. Thank your!
In C, types cannot specify default values for variables. Either you need to use C++ with a constructor, or to systematically initialize your variable when you instantiate it.
In C there no such thing as default values or constructors. You would have to write a function that initializes the struct
with some default values. Alternatively you can switch to C++ and make a constructor that would initialize the members of the struct
with some default values.
See here for information on what : 20
in unsigned int size: 20
mean.
Here is the wikipedia article on bit fields.
pratik’s suggestion will work (assuming his use of typedef
is a typo), but it leaves a global object floating around. An alternative technique:
struct d {
unsigned int size;
};
/* use only *one* of these next lines */
#define D (struct d){20} // C99
#define D {20} // C89
…
struct d foo = D; // in either case
The C99 version has the advantage that it can catch some misuse of the “constructor”, e.g.,
struct d {
unsigned int size;
};
#define D99 (struct d){.size = 20}
#define D89 {20}
…
float a[17] = D89; // compiles, but is that really what you meant?
float b[17] = D99; // will not compile
Also, you can use the “compound literal” technique to create more complicated constructors, perhaps with arguments.
For making a value of a structure member default u should use something similar to a constructor's concept in OOP languages..
typedef struct d {
unsigned int size;
} D{20};
This way you can specify default values for structure members wenever you create an object of that structure...
Hope it helps.. :)
精彩评论