c3c icon indicating copy to clipboard operation
c3c copied to clipboard

Toggling explicit struct initialization per struct via attribute

Open kulkalkul opened this issue 1 year ago • 5 comments

ZII is perfect for some tasks, but sometimes I know that given struct is always initialized. So, adding new fields to a struct definition adds possibility of breaking this guarantee as uninitialized fields can go unnoticed. It is possible to overcome this using initialization functions, but I find that it becomes necessity for such structs, makes those functions constructor-like. I also enjoy using struct initialization when possible.

As a solution, an attribute can be added for each struct initialization literal (pardon the term if wrong).

Struct definition (nothing special here):

struct Foo {
  int a;
  int b;
  int c;
  int d;
}

Expression:

@nopartial Foo {
  .a = 5,
  .b = 2,
  .d = 1,
  // compile error, as c is forgotten
}

Attribute at initialization location would allow same struct to be used with both ZII fields and explicit initialization, while preventing hard to follow bugs within big codebases.

kulkalkul avatar Nov 08 '24 02:11 kulkalkul

I am not sure how you mean the initializer, that is in no way correct C3.

lerno avatar Nov 08 '24 10:11 lerno

Foo foo = Foo { .a = 5, };

I'm talking about the part in right hand side. So, the above code would work as-is

Foo foo = Foo { .a = 5, } @nopartial;

This would error out as fields b, c, and d are missing (I don't know where is the good place for nopartial). So, this allows user to choose whether they want it partial or not per struct "initialization"

kulkalkul avatar Nov 08 '24 11:11 kulkalkul

That is indeed the right location from a parsing point of view. I only have some doubts as to whether it should be included. C has had .foo = 5 initialization for ages, so is there some similar attribute in GCC?

lerno avatar Nov 16 '24 09:11 lerno

I don't know, I'm unfortunately not a C programmer 😅 It was something that annoyed me while using Odin, that's why I asked about whether something similar exists in C3 (on discord), which prompted me to create the issue. I read that C3's goal is to stay compatible with C as much as it can, that's also the theme I get from your comment above; so in that case, I agree that it'd probably feel out of place for the language

kulkalkul avatar Nov 17 '24 06:11 kulkalkul

Adding attributes are in general fine. I just want to make sure all features are used.

lerno avatar Nov 17 '24 22:11 lerno