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

Pages: 1-4041-

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:02

You can with C++. Make x[ and y public float members, define the constructor for std::initializer_list, and overload the array indexing operator.

Name: Anonymous 2013-08-17 0:12

>>2 I figured there would be, but I don't want to use C++.

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;

Name: Anonymous 2013-08-17 0:48

>>1
You're doing it completely wrong. Use Clang/LLVM.

http://clang.llvm.org/docs/LanguageExtensions.html#vectors-and-extended-vectors

This is one of the reasons Sony picked Clang as the primary compiler for the Playstation 4.

If you're not using the SIMD capabilities of your CPU, why are you even programming?

Name: lars-lab.jpl.nasa.gov 2013-08-17 0:51

>>1
Why are you breaking the Standard?

#include <stdio.h>
#include <tgmath.h>

typedef struct {
   float x
   float y;
   float value[2]
} Vector;

int main(int argc, char *argv[]) {
    vector herp = {.x = 3, .y = 4}};
    printf("Vector: {%f, %f}\n", herp.x, herp.y);
    float length = sqrt(herp.x * herp.x + herp.y * herp.y);
    printf("Length: %f\n", length);
    v normalized = {.x = herp.val[0] / length, .y = herp.val[1] / length};
    printf("Normalized: {%f, %f}\n", normalized.value[0], normalized.value[1]);
}

The excerpt can be further optimized, which I am not going to do for you.

Name: Anonymous 2013-08-17 0:53

>>4
You can do something similar in C too.
#include <stdio.h>
#include <tgmath.h>
enum { X, Y, Z };
typedef float vec2[2];
int main(int argc, char *argv[]) {
    vec2 herp = {3, 4};
    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[0] / len, herp[1] / len};
    printf("Normalized: {%f, %f}\n", normalized[0], normalized[1]);
}

Name: Anonymous 2013-08-17 0:53

Also, for C++, official SIMD vector math standard library proposal, to be adopted as a TR for release in 2015, and inclusion into C++17. Adds Clang/OpenCL vector extensions for swizzling operators to the language, and a full math library, modeled after OpenCL.

http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3571.pdf

Name: Anonymous 2013-08-17 1:04

Use complex numbers as 2D vectors. Your sqrt(herp.x * herp.x + herp.y * herp.y) becomes fabs(herp) (with <tgmath.h>).
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/tgmath.h.html

Name: Anonymous 2013-08-17 1:53

>>5 I was going to look up GCC SIMD intrinsics later, but hoo-lee-shit this makes life easier for me. Simple vector-to-vector arithmetic, predefined vector data types (that also, I assume, have the proper static alignment already), and likely much better SIMD code generation than uses standard aligned structs or arrays would have given, and it's that easy? Thanks a billion for coming through for me /prog/, I was this close to ripping John Carmack's preprocessor macros from the Quake 3 engine source like an idiot. Instead, I can use very similar syntax to what I can do in GLSL or OpenCL, and I barely have to implement anything.

Though I must say, just from reading that document, this doesn't necessarily seem like an advantage of Clang over GCC to me, because GCC seems to support almost the same syntax for its vector intrinsics:
http://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html

>>7 That's a smart idea, too. This way, I can easily use the vector types for colors as well: enum { A, B, G, R};

>>8 That might tempt me to switch to "C-style C++" when it's released, if something similar isn't available as a GCC or Clang extension for C programs, but I guess I can get by with __builtin_shuffle / __builtin_shufflevector and some C11 type generic macros for now.

>>9 That wouldn't help at all for 3 element or 4 element vectors, though.

Name: Anonymous 2013-08-17 2:41

>>10
Clang also has an __attribute__((overloadable)) extension that lets you overload functions in C, just like in C++. So you don't need to use C11's funky generic macros like with tgmath.

You still need to build your own library of functions for things like sin, cos, tan, sqrt, pow, log, dot products, cross products, etc. you can just splat the builtin C99 math functions, or roll your own. For things like cross/dot, you need to use your platform's SIMD intrinsics (converting the the vector_type to __m128 for SSE, for example).

In the future, this will be supplied in the standard libraries with support for various CPU and GPU platforms (nVidia and AMD employees are working on http://libclc.llvm.org/ in their spare time, patches welcome).

Name: Anonymous 2013-08-17 2:43

>>10
GCC doesn't have GLSL/OpenCL shader-style swizzeling.

You can't do v.xxyy = u.wzxy.

Name: L. A. Calculus !!wKyoNUUHDOmjW7I 2013-08-17 2:57

>>12
GO SHOVE A SHADER UP UR ASS, ESKIL STEENBERG.

Name: Anonymous 2013-08-17 4:06

>>13
bite it, boy

Name: Anonymous 2013-08-17 4:18

*bites dick*

Name: Anonymous 2013-08-17 4:46

>>15
Oh God, my foreskin! What did you do, you swallowed it you scheming kike!

Name: Anonymous 2013-08-17 5:15

>>16
Don't worry. It'll grow back.

Name: Anonymous 2013-08-17 5:20

Thread full of idiots
- "Use C++"
- "NO I DONT WANT TO USE SUPERIOR TECHNOLOGY"
- "LOL EVERYONE KNOWS C IS BETTER"

Haha, idiot C++ haters. Enjoy your inferior language. I can reimplement your C shit with half smaller C++ code and better runtime performance.

Idiots.

Name: Anonymous 2013-08-17 5:38

>>18
I think umena factor C shit with half smaller C++ code. But if you can't see the equivalence between the two you are shit. Shit. Shit. Shit. SHIT!

Name: Anonymous 2013-08-17 6:27

Name: Anonymous 2013-08-17 7:33

>>20
Thank you, Anon! Great articles. Everyone here should read them five (5) times, before mentioning C/C++ as a valid solution next time.

Name: Anonymous 2013-08-17 12:08

>>18
Sometime tells me this is your first visit to the board, and that you come from /g/. This is a pretty bad board with no le funnay images, so what are you exactly doing here? I've heard you have programming threads on /g/.

Name: Anonymous 2013-08-17 13:21

>>20
before mentioning C/C++ as a valid solution next time.
Why are you including C into this? It has absolutely nothing to do with C++.

Name: Anonymous 2013-08-17 14:45

>>23
Haven't you heard? Nobody should use C or C++ anymore, its all about python, ruby, or ENTERPRISE JAVA

Name: Anonymous 2013-08-17 14:58

unions considered retarded. Use u8 arrays instead.

Name: Anonymous 2013-08-17 16:11

my dad was in a u8 array and even held the title of U8 Array Steward before he passed away and when a pallet fell on him and crushed his leg and he had to have surgery. he pulled through thought he had to be resusitated on the operating table. he passed in 1995. I DIDN'T SEE ANY U8 ARRAY LEADERS THERE FOR HIM. when the u8 array said STRIKE we scraped by for weeks with no pay.

Name: Anonymous 2013-08-17 16:17

>>26
u wot m8?

Name: Anonymous 2013-08-17 16:22

>>27
LELLLLL LE EGIN U WOT M8 MEME!
I LAF HARD! HIT HEAD ON TABLE AND BLOOD ERYWHERE!

Name: Anonymous 2013-08-17 19:41

Name: Anonymous 2013-08-17 19:42

Name: Anonymous 2013-08-18 6:43

>>20
Wow, instead of those old links, you should provide valid reasons to use C instead of C++.

Name: Anonymous 2013-08-18 7:26

>>31
IHBT

Name: Anonymous 2013-08-18 7:57

>>32
Calling people trolls provides nice idea shelter for shallow minded.

Name: Anonymous 2013-08-18 8:13

>>33
Wow, you are serious?

Name: Anonymous 2013-08-18 8:20

>>33
An open mind is like a fortress with it's gates wide open.

C++ might seem appealing, but it really is horrible.

Name: Anonymous 2013-08-18 8:34

>>35
sure, lets all just use C and never try anything better...

Name: Anonymous 2013-08-18 8:46

>>36
That's not what I said. The fact is, C++ programs are pretty much always bigger, slower an more memory hungry. C++ is also harder to read which makes developing them even slower than C. And C++11 only makes things worse.

Name: Anonymous 2013-08-18 9:21

>>31
it's faster, more readable, less deceptive, more documented, just as functional, simpler, more compact and easier to debug

Name: L. A. Calculus !!wKyoNUUHDOmjW7I 2013-08-18 9:28

So he didn't make it API like, or compartmentalize the project to multiple programs, with one engine to manage them all.
I'M TALKIN ABOUT mupen64plus. ALL I KNO IS DAT IS PRINTS SHIT TO stdout.

And I meant the K&R indentation style:
NEVER PUT MUCH THOUGHT INTO DAT. WATEVER FIRES UR FUCKIN ROCKET.

I'd figured you know one you use often than the standard library.
ALL I NEEDS FOR MOST PROGRAMS IS DA STANDARD C LIBRARY. SOMETIMES I COPY SMALL SNIPPETS FOR DATA STRUCTERS, PACKING/UNPACKING INTEGERS IN A BINARY FORMAT, AND DA STRING FUNCTIONS DEY LEFT OUT OF string.h. OR I JUST USE LITHP.

Here are some listings:
Ruby JavaScript node.js Ruby on Rails Python CSS iOS API HTML5 jQuery
GET UR STUPID YUPPIE SHIT OUTTA MY THRED, YA FUCKIN RETOID.

Name: Anonymous 2013-08-18 9:31

WRONG THRED. PUT DAT IN UR PIPE AND SMOKE IT, U FUCKIN YUPPIES. MAYBE U CAN START COMPARING PENIS SIZE INSTEAD OF WICH LANGUAGE FUCKS U IN DA ASS EVERY NITE.

Name: Anonymous 2013-08-18 12:05

>>37
The fact is, C++ programs are pretty much always bigger, slower an more memory hungry
Well you know C++ is typically used in LARGER projects and a lot of projects will prefer vectors and strings over cstrings and arrays. It's expected.
And C++11 only makes things worse.
C++11 makes C++ usable. Move semantics. Type inference. Lambas. Constexprs. etc.

Name: Anonymous 2013-08-18 12:54

>>41
LARGER projects [...] will prefer vectors and strings over cstrings and arrays.
Big projects should use neither C nor C++ if not absolutely necessary. This proves nothing.

Move semantics
Only needed because of a stupid C heirloom that crippled C++ as a language from the get-go.

Type inference
Should have been added as soon as the STL was made. The fact that someone thought having to write vector<type>::iterator in every for-loop on things like vectors shows that this language is designed so badly it's not even funny.

Lambdas
Are flaky as hell, utilize awful syntax as lambdas have problems with the ALGOL style and require ridiculous attention to detail because they are brought into an inferior imperative language.

Constexprs
Because C++ obviously needs even more compiler optimization keywords. It's like Fortran all over again, only worse designed.

Name: Anonymous 2013-08-18 14:24

>>42
well LE SAGER GUY, >>41 is right and you have no correct arguments against. faggot.

Name: Anonymous 2013-08-18 14:32

>>43
Of course you are right when you say nothing.

Name: Anonymous 2013-08-18 15:04

>>44

LLLLLLLLEEEEEEEEEEEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLLLLLLLLLLLL
XDXDXDD LE SAGE LELELELELEL SAGE
ISAGED DOWNVOTED UX XDXDXDXDXDXDX
NO BUMPS FOR YA XDXD LE SAGEEEDDD
TROLFLACE 9GAG LXDXDL GET BACK TO /G/EDDIT FACE XD LEEEEEEEEEEEEELLLLLLLLL
I DOWNVOTED U SAGEE XDXDXD

Name: Anonymous 2013-08-18 15:08

>>45
Back to the imagereddits with you.

Name: Anonymous 2013-08-18 15:44

>>45
You can't even imitate lelcunt well. Fuck off, the lelspam was never a /prog/ meme, like you retards like to call it.

Name: Anonymous 2013-08-18 15:46

LE SAGER GUY
Do you retards actually think this is some sort of insult? Pretty sure many imagereddit users love using sage too.

Name: DooM Guy 2013-08-18 16:05

>>46
Back to Hell with You! *Bang* *reloads shotgun*

Name: Anonymous 2013-08-18 18:25

>>48
Is this le birth of le new le/g/in meme?

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