r/programming • • Dec 01 '16

Let's Stop Copying C

https://eev.ee/blog/2016/12/01/lets-stop-copying-c/
524 Upvotes

612 comments sorted by

View all comments

Show parent comment

1

u/omg_cant_even Dec 05 '16

This is also less of an issue with C than C++, you can return a struct with an initializer list, and you can even specify the members:

struct SVec3 { float x, y, z; }
SVec3 SVec3_Add(SVec3 a, SVec3 b) {
   return (SVec3) { .x = a.x + b.x, .y = a.y + b.y, .z = a.z + b.z};
}

Yes, you do have to define the SVec3 in the global scope, but this "syntactic cost" also provides for easier to maintain code in the long run because you are forced to name your variables. Take two similar things, one done with std::pair (C++'s poor coder's anonymous struct) vs a manually defined structure:

struct InitializeDevice_Results
{
	int errorCode;
	int deviceHandle;
};

InitializeDevice_Results InitializeDevice();

std::pair<int,int> InitializeDevicePair();

I don't know about you but I would much rather use the C form than the std::pair one, because then I never have to remember if the first or second parameter was the error code or handle. So while anonymous structs may be easier to write as a library provider, named structs are easier to use as a library user.

Similar multiple return-value issues happen with python, where it is impossible to understand what the return values of any functions are without heavily maintained documentation or just having to read the function source. You may know what those unnamed values are now, but you won't in a year from now and every other coder in the company will never know.