4 ms·
What's the difference? My understanding is as follows: A struct is a tuple. It's just some structured memory. Where a tuple would be indexed numerically, a stru
by chewxy 7y ago
What's the difference? My understanding is as follows: A struct is a tuple. It's just some structured memory. Where a tuple would be indexed numerically, a struct is indexed with names of the fields (equiv in Python to NamedTuple)
- rwmj 7y agoWhat happens under the hood would be the same, but in C you have to define a new struct for each return type which is clunky. In ML or Python you can return ad hoc tuples, eg: let res, _, _ = fun_which_returns_3_tuple () vs struct my_result { int res; int other; int third; }; ... struct my_result r = fun_which_returns_struct (); printf ("%d\n", r.res);
- deleted 7y ago[deleted]
- jacquesm 7y agoTuples can pull their contents from different memory locations whereas structs are laid out continuously in memory (modulo padding if enabled). Of course you could store pointers in the structs you return but that would defeat the whole 'single return' concept, then you may as well return a pointer to a struct which is ugly because it will never be thread safe and is a particularly nice pitfall regarding ownership of that struct. So either return the whole struct as values or, alternatively - and this is the way most library functions do it - call the function with a pointer to an empty struct which the function then fills. That leaves the return value for error status.
- layoutIfNeeded 7y ago> So either return the whole struct as values or, alternatively - and this is the way most library functions do it - call the function with a pointer to an empty struct which the function then fills. Mind you, under the hood all your structs will be returned through pointers to caller-allocated memory, unless it can fit into 8 bytes. “To return a user-defined type by value in RAX, it must have a length of 1, 2, 4, 8, 16, 32, or 64 bits. [...] Otherwise, the caller assumes the responsibility of allocating memory and passing a pointer for the return value as the first argument.” https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=vs-2019#return-values https://docs.microsoft.com/en-us/cpp/build/x64-calling-conve...
- jacquesm 7y agoYes, but that's literally an implementation detail and this could be done in many different ways. The idea here is to gain some amount of expressiveness, if that is the goal then implementation details should be of lesser importance. Moving structures around 'by value' rather than 'by reference' is wasteful in my view, but if you have to then you should no longer worry about the underlying mechanism until optimization time rolls around.
- lilyball 7y ago> Tuples can pull their contents from different memory locations I'm not sure what you mean by this. Tuples are typically isomorphic to structs with unnamed fields.