"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Compile C Code with Anonymous Structs or Unions?

How Can I Compile C Code with Anonymous Structs or Unions?

Published on 2024-11-08
Browse:879

How Can I Compile C Code with Anonymous Structs or Unions?

Compiling C Code with Anonymous Structs/Unions

The question arises regarding how to compile C code with anonymous structs or unions, as demonstrated in C with anonymous fields using unions. In C, an attempt to create a similar structure using named structs containing an anonymous union results in compilation errors.

The error messages indicate that the anonymous union and struct fields are not declared within the struct declaration. To enable this feature in C, it is necessary to use the -fms-extensions compiler flag.

Revised Code with -fms-extensions

#include 
#include 

typedef struct {
    union {
        float x, y, z;
    } xyz;
} Vector3;

int main() {
    Vector3 v;
    assert(&v.xyz.x == &v.x);
    assert(&v.xyz.y == &v.y);
    assert(&v.xyz.z == &v.z);
    return 0;
}

With this modification, the code will compile successfully, and the assertions will pass, confirming that the addresses of the union members and the struct fields are equivalent.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3