About default C struct values, what about this code?

后端 未结 8 1512
时光说笑
时光说笑 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 16:10

    ... create structs with default values ...

    That is impossible in C. A type cannot have default values. Objects of any type cannot have a default value other than 0, though they can be initialized to whatever is wanted.
    The definition of a struct is a definition of a type, not of an object.


    What you asking is about the same thing as a way to have ints default to, say, 42.

    /* WRONG CODE -- THIS DOES NOT WORK */
    typedef int int42 = 42;
    int42 a;
    printf("%d\n", a); /* print 42 */
    

    Or, adapting to your example

    /* WRONG CODE -- THIS DOES NOT WORK */
    struct stuff {
        int42 stuff_a;
        int65536 stuff_b;
    }
    struct stuff a;
    printf("%d\n", a.stuff_b); /* print 65536 */
    

提交回复
热议问题