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:
Copystruct MyStruct_s
{
int id;
} MyStruct_default = {3};
typedef struct MyStruct_s MyStruct;
And then always initialize your new instances as:
CopyMyStruct mInstance = MyStruct_default;
Answer from Alok Save on Stack OverflowStructure 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:
Copystruct MyStruct_s
{
int id;
} MyStruct_default = {3};
typedef struct MyStruct_s MyStruct;
And then always initialize your new instances as:
CopyMyStruct mInstance = MyStruct_default;
you can not do it in this way
Use the following instead
Copytypedef 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.
Copytypedef 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:
CopyINIT_EMPLOYEE(emp);
I wasn't able to find a straight answer if struct have or haven't any default values, by default. Like, 0 for int and NULL for pointers.
So for this code:
// void pointers as generic Items
typedef void *Item;
typedef const void *constItem;
typedef struct tnode *Tree;
typedef const struct tnode *constTree;
typedef struct tnode {
Item value;
Tree sub[2];
} Treenode;
typedef enum {left, right} Child;And this in the main function:
int main()
{
Tree wtree; // It's a pointer to a struct not a struct
wtree->value = NULL;
wtree->sub[left] = wtree->sub[right] = NULL;
return 0;
}Is it necessary to initiate this way for this example where NULL is the initial value? Is this the best way to initiate a structure with a pointer to it?
How to initialize C structs with default values - Stack Overflow
[ENH] Specify default values for C struct declarations
How to set an initial value of a variable of struct in C? - Raspberry Pi Stack Exchange
initialization - Default values in a C Struct - Stack Overflow
In C, whether an object is initialized or not depends on how you declare the object, for example whether you declare it as an object of static storage duration (which is initialized to zero unless you explicitly initialize it to something else) or an object of automatic storage duration (which is not initialized, unless you explicitly initialize it).
Therefore, it would not make sense to assign default values to the type definition, because even if the language allowed this, it would not guarantee that the object of that type will be initialized.
However, you can create your own function which initializes your struct to specific values:
void init_list( List *p )
{
p->size = 0;
p->head = NULL;
p->tail = NULL;
}
Assuming that the object is declared inside a function (not at file scope), you can use the following code to declare and initialize the object to default values:
List list1;
init_list( &list1 );
If the object is declared at file scope, you can't call the function init_list at file scope, but you can call the function inside the function main, for example.
Alternatively, when you declare the object, you can also initialize the individual members:
List list1 = { 0, NULL, NULL };
This will also work at file scope.
Since everything is being initialized to zero, it is sufficient to write the following:
List list1 = { 0 };
In that case, all members that are not explicitly assigned a value will be initialized to zero.
In C opposite to C++ you may not initialize data members in structure declarations like you are doing
typedef struct List {
int size = 0;
Node* head = NULL;
Node* tai = NULL;
} List;
Also it does not make sense to declare the global pointer list1.
List* list1;
What you need is to write
typedef struct List {
int size;
Node* head;
Node* tail; // I think you mean `tail` instead of `tai`
} List;
int main( void )
{
List list1 = { .size = 0, .head = NULL, .tail = NULL };
//...;
While macros and/or functions (as already suggested) will work (and might have other positive effects (i.e. debug hooks)), they are more complex than needed. The simplest and possibly most elegant solution is to just define a constant that you use for variable initialisation:
const struct foo FOO_DONT_CARE = { // or maybe FOO_DEFAULT or something
dont_care, dont_care, dont_care, dont_care
};
...
struct foo bar = FOO_DONT_CARE;
bar.id = 42;
bar.current_route = new_route;
update(&bar);
This code has virtually no mental overhead of understanding the indirection, and it is very clear which fields in bar you set explicitly while (safely) ignoring those you do not set.
You can change your secret special value to 0, and exploit C's default structure-member semantics
struct foo bar = { .id = 42, .current_route = new_route };
update(&bar);
will then pass 0 as members of bar unspecified in the initializer.
Or you can create a macro that will do the default initialization for you:
#define FOO_INIT(...) { .id = -1, .current_route = -1, .quux = -1, ## __VA_ARGS__ }
struct foo bar = FOO_INIT( .id = 42, .current_route = new_route );
update(&bar);
A compiler isn't required to give you a diagnostic for this. Good compilers do. There is nothing different between regular variables and structs, if they are at local scope (automatic storage duration), they will contain garbage values. Using those values could invoke undefined behavior.
The only thing that makes structs different is that if you initialize at least one of the members, the rest of the members will get set to zero (initialized as if they had static storage duration). But that's not the case when none of the members are initialized.
No, they are not initialized to any defaults. You can say compilers as well as standard lack in ability to detect such issues and don't render any warning. May be for the compiler writers it was easy to check on ordinary (basic) datatypes and not for UDT.
Code Analysis tool may give the warnings on such scenarios. CppCheck for example.
If you want to set a struct object in one go and you have a C99 compiler, try this:
struct stuff {
int stuff_a;
int stuff_b;
// and so on...
};
struct stuff foo;
/* ... code ... */
foo = (struct stuff){.stuff_b = 42, .stuff_a = -1000};
Otherwise, with a C89 compiler, you have to set each member one by one:
foo.stuff_b = 42;
foo.stuff_a = -1000;
Running example @ ideone : http://ideone.com/1QqCB
The original line
struct a{ a() : i(0), j(0) {} INT i; INT j;}
is a syntax error in C.
As you have probably learned from the other answers, in C you can't declare a structure and initialize it's members at the same time. These are different tasks and must be done separately.
There are a few options for initializing member variables of a struct. I'll show a couple of ways below. Right now, let's assume the following struct is defined in the beginning of the file:
struct stuff {
int stuff_a;
int stuff_b;
};
Then on your main() code, imagine that you want to declare a new variable of this type:
struct stuff custom_var;
This is the moment where you must initialize the structure. Seriously, I mean you really really must! Even if you don't want to assign specific values to them, you must at least initialize them to zero. This is mandatory because the OS doesn't guarantee that it will give you a clean memory space to run your application on. Therefore, always initialize your variables to some value (usually 0), including the other default types, such as char, int, float, double, etc...
One way to initialize our struct to zero is through memset():
memset(&custom_var, 0, sizeof(struct stuff));
Another is accessing each member individually:
custom_var.stuff_a = 0;
custom_var.stuff_b = 0;
A third option, which might confuse beginners is when they see the initialization of struct members being done at the moment of the declaration:
struct stuff custom_var = { 1, 2 };
The code above is equivalent to:
struct stuff custom_var;
custom_var.stuff_a = 1;
custom_var.stuff_b = 2;
You don't even need to define a constructor
struct foo {
bool a = true;
bool b = true;
bool c;
} bar;
To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.
Yes. bar.a and bar.b are set to true, but bar.c is undefined. However, certain compilers will set it to false.
See a live example here: struct demo
According to C++ standard Section 8.5.12:
if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value
For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.
If you don't really want undefined bar.c to start with, you should also initialize it like you did for bar.a and bar.b.