Initializing Default Values in a Struct

Initializing default values in a struct

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.

default value for struct member in C

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;

Can't initialize a struct with a default value

Swift 5.1:

Variables, marked with var are optional in constructors and their default value will be used. Example:

struct Struct {
var param1: Int = 0
let param2: Bool
}

let s1 = Struct(param2: false) // param1 = 0, param2 = false
let s2 = Struct(param1: 1, param2: true) // param1 = 1, param2 = true

For older versions of Swift (< 5.1):

Default Initialization is all-or nothing for a Struct. Either you define defaults for all properties and you get an automatically generated initializer Struct1() plus an initializer with all of the properties, or you get only the initializer with all of the properties, including any that happen to have a set default value. You're going to have to implement a custom initializer.

struct Struct1 {
let myLet = "my let"
let myLet2: Bool
let myLet3: String

init(myLet2: Bool, myLet3: String) {
self.myLet2 = myLet2
self.myLet3 = myLet3
}
}

How to set default values in Go structs

  1. Force a method to get the struct (the constructor way).

    From this post:

    A good design is to make your type unexported, but provide an exported constructor function like NewMyType() in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.

    This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.

  2. Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.

default value in struct and the constructor order

The order initialization happens in is quite rigid, it is always the order the members are declared in.

First of all, all default in-class initializers are applied (in the order that members are declared) unless overruled by the initialization list.

Then the constructors initialization list is used and any members listed there are initialized in the order they are declared. If any of those listed members also have in-class initializers, then those don't happen and the initialization list wins and is used to initialize the members.

Then the constructor body is executed. At this point all members are already initialized, either by in-class initialization or the initializer list. But the constructor body can choose to assign new values to those initialized members.

In any case, for a given member foo it will be initialized by the in class initialization (if any) or by the initialization list (if any) or it will be default initialized. Regardless of the method used to initialize it, that initialization will always happen after another member declared before it and before another member declared after it.

For example:

struct s {
int a = 1;
int b = 42;
int c = 666;
int d;
int e;
s() : e(3), b(123) {
c = 7;
}
};

The above will always initialize a first and since it has an in-class initializer, that will be used. It's value will be 1.

b is initialized second. It has an in-class initializer, but the constructors initialization list overrules that. It will be initialized to the value 123.

Then c is initialized to the value 666.

d is uninitialized / or rather; default initialized, which for a int is the same as uninitialized, but for other types like std::string means initialized to an empty string - it depends on the type whether you have a usable value or not.

Then e is initialized to the value 3. This happens last because it is declared last. The order it is listed in in the initialization list of the constructor is irrelevant.

Then the constructor body is executed and c is assigned the value 7. So it is both initialized and subsequently assigned to - this is usually inefficient.

The object construction is now complete.

Default values in struct c [duplicates]

If you don't specify enough initializers for all members of a struct, you'll face Zero initialization, which will initialize remaining members to 0. I think by today's standards this seems a bit odd, especially because C++'s initialization syntax has evolved and matured a lot over the years. But this behavior remains for backwards-compatibility.

C# struct default values

Update: In C# 10+ (.NET 6+) this limitation is lifted. You now can have default constructors on structs, and you also can initialize fields and properties in place. Write your struct as if it was a class, and it will work:

public struct OptionsStruct
{
public int ItemA { get; set; } = 2;
public int ItemQ { get; set; } = 2;
}
    SetOptions(new OptionsStruct()
{
ItemA = 3,
// ...all other fields have default values.
});

However, there are 2 gotchas to be aware of:

  • If you have no constructors or a parameter-less constructor on your struct, the field and property initializations will work fine. But, they won't work if you have a constructor with parameters but no parameter-less constructors. If you have a with-parameter constructor, also write a parameter-less constructor (even if it's empty), so when you write new MyStruct(), the fields and properties are initialized as you expect. (This behavior is there to keep backward compatibility with the previous behavior of not calling a constructor when all parameters are optional. See the last code block on this answer for an example.)

    public struct NoConstructor
    {
    public int Item { get; set; } = 42;
    }

    public struct ParameterlessConstructor
    {
    public int Item { get; set; } = 42;

    public ParameterlessConstructor() { }
    }

    public struct WithParameterConstructor
    {
    public int Item { get; set; } = 42;

    public WithParameterConstructor(int item)
    {
    Item = item;
    }
    }

    public struct BothConstructors
    {
    public int Item { get; set; } = 42;

    public BothConstructors() { }

    public BothConstructors(int item)
    {
    Item = item;
    }
    }
        Console.WriteLine(new NoConstructor().Item); // 42
    Console.WriteLine(new ParameterlessConstructor().Item); // 42
    Console.WriteLine(new WithParameterConstructor().Item); // 0
    Console.WriteLine(new BothConstructors().Item); // 42
  • The parameter-less constructor is not guaranteed to be always called, so don't rely on your fields and properties being always initialized. If you create an array of a struct, like new MyStruct[5], or if you use default or default(MyStruct), no constructor will be called and the field and properties will be initialized to default values (0 or false or null), just like how it would be before C# 10.

    public struct MyStruct
    {
    public int FortyTwo { get; } = 42;

    public int GetFortyThree()
    {
    return FortyTwo + 1;
    }
    }

    public class SomeClass
    {
    MyStruct myStruct; // not initialized, same as default(MyStruct)

    public int GetFortyThree()
    {
    return myStruct.GetFortyThree();
    }
    }
        Console.WriteLine(new MyStruct().GetFortyThree()); // 43
    Console.WriteLine(default(MyStruct).GetFortyThree()); // 1
    var array = new MyStruct[5];
    Console.WriteLine(array[0].GetFortyThree()); // 1
    Console.WriteLine(new SomeClass().GetFortyThree()); // 1

Here's the link to the docs on the new C# 10 / .NET 6 feature: Parameterless constructors and field initializers

For C# 9 and below, read on...


The limitation on structs is that you cannot have a default constructor. So you cannot set default values to the fields and properties (because that is compiled into the default constructor).

But you can have a non-default constructor, i.e. a constructor that takes parameters.

So you can have a struct like this:

public struct OptionsStruct
{
public int ItemA { get; set; }
public int ItemQ { get; set; }

public OptionsStruct(bool useDefaults)
{
if (useDefaults)
{
ItemA = 2;
ItemQ = 2;
}
else
{
ItemA = 0;
ItemQ = 0;
}
}
}

And use it as you wrote:

    SetOptions(new OptionsStruct(useDefaults:true)
{
ItemA = 3,
// ...all other fields have default values.
});

Another way to go is to have a static method that sets the default values:

public struct OptionsStruct
{
public int ItemA { get; set; }
public int ItemQ { get; set; }

public static OptionsStruct GetDefault()
{
return new OptionsStruct()
{
ItemA = 2;
ItemQ = 2;
};
}
}

And use it like this:

    var options = OptionsStruct.GetDefault();
options.ItemA = 3;
SetOptions(options);

If the number of your properties is not too much, you can also use a constructor with optional parameters:

public struct OptionsStruct
{
public int ItemA { get; set; }
public int ItemQ { get; set; }

public OptionsStruct(int itemA = 2, int itemQ = 2)
{
ItemA = itemA;
ItemQ = itemQ;
}
}

But it will only be called if you give it at least one parameter:

    var options1 = new OptionsStruct(); // The "default" constructor is called, so everythng will be 0.
Console.WriteLine(options1.ItemA); // 0
Console.WriteLine(options1.ItemQ); // 0

var options2 = new OptionsStruct(3); // Everything works as expected.
Console.WriteLine(options1.ItemA); // 3
Console.WriteLine(options1.ItemQ); // 2

How to create a structure initialized with default values?

The response from AlThomas:

"Structs in Vala can have initializers (similar to a constructor for a class) and methods. So what I can extract from your second pastebin you could write that as:"

struct First {
int data;
int pos;

public First (int[] mass) {
data= 5;
pos = mass.length;
}

public int sas () {
return data + pos;
}
}

void main () {
int[] a = {1,3,0,1,2,3,2,1};
var b = First (a);
print (@"$(b.sas ())\n");
}


Related Topics



Leave a reply



Submit