Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it proper to initialize variables in a structure define in typedef (C programming)

typedef struct
{
    int id = 0;
    char *name = NULL;
    char *department = NULL;
    int phone = 0;
} emp;

In C programming is it a good programming practice to do something like that, or, should I initialize when I declare the variable 'emp'.

I am using a GCC compiler and the above code does compile. I want to know if it is the proper way of initializing.

like image 934
yogisha Avatar asked Sep 11 '25 04:09

yogisha


1 Answers

With typedef struct { ... } emp; you are creating a new complex type called "emp". When you declare a variable of type "emp", that is where you typically initialize it.

I would go with:

typedef struct
{
  int id;
  char *name;
  char *department;
  int phone;
} emp;

emp myVar = { 
  /* id */ 0, 
  /* name */ NULL, 
  /* department */, NULL, 
  /* phone */ 0 
};
like image 137
GrandAdmiral Avatar answered Sep 13 '25 00:09

GrandAdmiral