1

Here I have the following struct

typedef struct d {
    unsigned int size:  20;
} D;

the question is how the default variable size be 10. Thank your!

yasouser
  • 5,113
  • 2
  • 27
  • 41
Charlie Epps
  • 3,595
  • 9
  • 33
  • 38

5 Answers5

2

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.

Charles Brunet
  • 21,797
  • 24
  • 83
  • 124
1

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.

detunized
  • 15,059
  • 3
  • 48
  • 64
1

See here for information on what : 20 in unsigned int size: 20 mean.

Here is the wikipedia article on bit fields.

yasouser
  • 5,113
  • 2
  • 27
  • 41
1

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.

Community
  • 1
  • 1
J. C. Salomon
  • 4,143
  • 2
  • 29
  • 38
0

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.. :)

pratik
  • 119
  • 10