Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C - Union of struct and array, ugly syntax

Name: Anonymous 2013-08-16 23:57

I'm writing some floating pointer vector types in C. Using a union, I can get both struct and array representations of the same type, depending on which is more convenient. The syntax is very ugly, though:

#include <stdio.h>
#include <tgmath.h>
typedef union {
    struct { float x, y; };
    float val[2];
} vec2;
int main(int argc, char *argv[]) {
    vec2 herp = {{3, 4}}; // using {3, 4} throws an error when -Wall is enabled
    printf("Vector: {%f, %f}\n", herp.x, herp.y);
    float len = sqrt(herp.x * herp.x + herp.y * herp.y);
    printf("Length: %f\n", len);
    vec2 normalized = {{herp.val[0] / len, herp.val[1] / len}};
    printf("Normalized: {%f, %f}\n", normalized.val[0], normalized.val[1]);
}


Is there any way, using C99, C11, or possibly even GNU C extensions, that I can get syntax like the following?

vec2 derp = {6, 20}; // no need for two sets of braces in initializers
derp[0] = 5; // "anonymous" array


or am I better off making my vectors only structs or only arrays, and casting them to the other type when the alternative syntax is more convenient? (.x and .y are more convenient most of the time, but treating them as arrays will be more convenient for operations between vectors and matrices)

I know this is trivial shit but I want to get it right before I go any further.

Name: Anonymous 2013-08-17 0:36

>>2
C++
No thank you!

>>1
The union idea is nice, but technically it's still undefined behaviour using the union like that.



type Axis is (X, Y, Z);
for Axis use (X => 0, Y => 1, Z => 2);
type Vector_2D is array (X .. Y) of Float;

Vec : Vector_2D;

--  Indexed using either X, Y, or Z.
Vec (X) := 3.14;

--  Can loop over the axes in a vector with a for loop.
for N in Vec'Range loop
   Do_Something (Vec (N));
end loop;

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List