About default C struct values, what about this code?

后端 未结 8 1477
时光说笑
时光说笑 2020-12-31 15:27

I\'m trying to create structs with default values. I don\'t know how to accomplish this because every code that I see, is about initialising, and I would it for the natural

8条回答
  •  温柔的废话
    2020-12-31 15:55

    Type initializer is not possible in C.

    • A value must be stored in the memory.
    • A type does not occupy memory, what occupies memory is a variable of that type.

      struct stuff; is a type; it does not occupy memory

      struct stuff aStuff; is a variable of that type; aStuff occupies memory

    • Because a type does not occupy memory, it is not possible to save values into a type.

    • If there is syntactic sugar to support store/initialize values into a type then there must be additional code that is inserted to assign values to every instant variables of that type (e.g: in constructor in C++). This will result in a less efficient C if this feature is available.

    • How often do you need to retain this default values? I think it is unlikely. You can create a function to initialize variable with the default values or just initialize every fields with the values you want. So type initializer is not fundamental thing. C is about simplicity.

提交回复
热议问题