134

Is it possible to set default values for some struct member? I tried the following but, it'd cause syntax error:

typedef struct
{
  int flag = 3;
} MyStruct;

Errors:

$ gcc -o testIt test.c 
test.c:7: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
test.c: In function ‘main’:
test.c:17: error: ‘struct <anonymous>’ has no member named ‘flag’
user1508893
  • 9,223
  • 14
  • 45
  • 57

16 Answers16

184

Structure is a data type. You don't give values to a data type. You give values to instances/objects of data types.
So no this is not possible in C.

Instead you can write a function which does the initialization for structure instance.

Alternatively, You could do:

struct MyStruct_s 
{
    int id;
} MyStruct_default = {3};

typedef struct MyStruct_s MyStruct;

And then always initialize your new instances as:

MyStruct mInstance = MyStruct_default;
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 4
    If I have a global array: 'MyStruct arr[MAX_SIXE];', how can the function be used? (NOte: I cannot have an init() function that would go thru all the member and set the flag) – user1508893 Dec 05 '12 at 05:54
  • 20
    MyStruct_default should be declared as const. – Lundin Dec 05 '12 at 07:40
  • 1
    Thanks for your answer. Ended up making a code sandbox to test it out online, had trouble connecting everything at first, hope this helps someone else : https://ideone.com/knQ7xS – HoldOffHunger Jun 28 '18 at 23:46
64

you can not do it in this way

Use the following instead

typedef struct
{
   int id;
   char* name;
}employee;

employee emp = {
.id = 0, 
.name = "none"
};

You can use macro to define and initialize your instances. this will make easiier to you each time you want to define new instance and initialize it.

typedef struct
{
   int id;
   char* name;
}employee;

#define INIT_EMPLOYEE(X) employee X = {.id = 0, .name ="none"}

and in your code when you need to define new instance with employee type, you just call this macro like:

INIT_EMPLOYEE(emp);
mihai
  • 4,592
  • 3
  • 29
  • 42
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 1
    Not seems good if you want pass to parameter not accomplish the requirements. –  Dec 01 '16 at 16:57
20

I agree with Als that you can not initialize at time of defining the structure in C. But you can initialize the structure at time of creating instance shown as below.

In C,

struct s {
    int i;
    int j;
};

struct s s_instance = { 10, 20 };

in C++ its possible to give direct value in definition of structure shown as below

struct s {
    int i;
    s(): i(10) {}
};
pevik
  • 4,523
  • 3
  • 33
  • 44
Chirag Desai
  • 1,249
  • 1
  • 10
  • 22
18

You can do:

struct employee_s {
  int id;
  char* name;
} employee_default = {0, "none"};

typedef struct employee_s employee;

And then you just have to remember to do the default initialization when you declare a new employee variable:

employee foo = employee_default;

Alternatively, you can just always build your employee struct via a factory function.

Donnie
  • 45,732
  • 10
  • 64
  • 86
15

Create a default struct as the other answers have mentioned:

struct MyStruct
{
    int flag;
}

MyStruct_default = {3};

However, the above code will not work in a header file - you will get error: multiple definition of 'MyStruct_default'. To solve this problem, use extern instead in the header file:

struct MyStruct
{
    int flag;
};

extern const struct MyStruct MyStruct_default;

And in the c file:

const struct MyStruct MyStruct_default = {3};

Hope this helps anyone having trouble with the header file.

David Callanan
  • 5,601
  • 7
  • 63
  • 105
9

If you are using gcc you can give designated initializers in object creation.

typedef struct {
    int id = 0;
    char *name = "none";
} employee;

employee e = {
    .id = 0;
    .name = "none";
};

Or , simply use like array initialization.

employee e = {0 , "none"};

pevik
  • 4,523
  • 3
  • 33
  • 44
Omkant
  • 9,018
  • 8
  • 39
  • 59
  • 1
    I've seen some code also use colons for designated initializers, more in this question: http://stackoverflow.com/questions/1601201/c-struct-initialization-using-labels-it-works-but-how-documentation – sdaau Nov 20 '13 at 13:15
6

Even more so, to add on the existing answers, you may use a macro that hides a struct initializer:

#define DEFAULT_EMPLOYEE { 0, "none" }

Then in your code:

employee john = DEFAULT_EMPLOYEE;
Bogdan Alexandru
  • 5,394
  • 6
  • 34
  • 54
3

You can implement an initialisation function:

employee init_employee() {
  empolyee const e = {0,"none"};
  return e;
}
bitmask
  • 32,434
  • 14
  • 99
  • 159
  • 3
    Sorry, but that's just wrong @ecle. The return value is a naked struct, not a pointer. It will be copied, not returned by reference. Honestly, the compiler will probably optimise the heck out of it. – bitmask Jul 05 '17 at 08:39
  • @bismask Don't get me wrong..I did mention if the function returns a pointer **if it is a pointer**. Maybe you've commented on my previous comment before my recent edit. – ecle Jul 07 '17 at 01:16
3

You can use combination of C preprocessor functions with varargs, compound literals and designated initializers for maximum convenience:

typedef struct {
    int id;
    char* name;
} employee;

#define EMPLOYEE(...) ((employee) { .id = 0, .name = "none", ##__VA_ARGS__ })

employee john = EMPLOYEE(.name="John");  // no id initialization
employee jane = EMPLOYEE(.id=5);         // no name initialization
Maxim Kulkin
  • 2,698
  • 22
  • 11
3

If you only use this structure for once, i.e. create a global/static variable, you can remove typedef, and initialized this variable instantly:

struct {
    int id;
    char *name;
} employee = {
    .id = 0,
    .name = "none"
};

Then, you can use employee in your code after that.

ChrisZZ
  • 1,521
  • 2
  • 17
  • 24
2

You can use some function to initialize struct as follows,

typedef struct
{
    int flag;
} MyStruct;

MyStruct GetMyStruct(int value)
{
    MyStruct My = {0};
    My.flag = value;
    return My;
}

void main (void)
{
    MyStruct temp;
    temp = GetMyStruct(3);
    printf("%d\n", temp.flag);
}

EDIT:

typedef struct
{
    int flag;
} MyStruct;

MyStruct MyData[20];

MyStruct GetMyStruct(int value)
{
    MyStruct My = {0};
    My.flag = value;
    return My;
}

void main (void)
{
    int i;
    for (i = 0; i < 20; i ++)
        MyData[i] = GetMyStruct(3);

    for (i = 0; i < 20; i ++)
        printf("%d\n", MyData[i].flag);
}
Adeel Ahmed
  • 1,591
  • 8
  • 10
1

Another approach, if the struct allows it, is to use a #define with the default values inside:

#define MYSTRUCT_INIT { 0, 0, true }

typedef struct
{
    int id;
    int flag;
    bool foo;
} MyStruct;

Use:

MyStruct val = MYSTRUCT_INIT;
CSharpino
  • 11
  • 2
0

An initialization function to a struct is a good way to grant it default values:

Mystruct s;
Mystruct_init(&s);

Or even shorter:

Mystruct s = Mystruct_init();  // this time init returns a struct
Israel Unterman
  • 13,158
  • 4
  • 28
  • 35
  • If I have a global array: 'MyStruct arr[MAX_SIXE];', how can the function be used? (NOte: I cannot have an init() function that would go thru all the member and set the flag) – user1508893 Dec 05 '12 at 06:22
0

Another approach to default values. Make an initialization function with the same type as the struct. This approach is very useful when splitting large code into separate files.

struct structType{
  int flag;
};

struct structType InitializeMyStruct(){
    struct structType structInitialized;
    structInitialized.flag = 3;
    return(structInitialized); 
};


int main(){
    struct structType MyStruct = InitializeMyStruct();
};
Agriculturist
  • 521
  • 9
  • 20
0

You can create a function for it:

typedef struct {
    int id;
    char name;
} employee;

void set_iv(employee *em);

int main(){
    employee em0; set_iv(&em0);
}

void set_iv(employee *em){
    (*em).id = 0;
    (*em).name = "none";
}
Joseph Pena
  • 167
  • 2
  • 8
-9

I think the following way you can do it,

typedef struct
{
  int flag : 3;
} MyStruct;
Shibu J
  • 3
  • 1