Timeline for Why do many functions that return structures in C, actually return pointers to structures?
Current License: CC BY-SA 3.0
7 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Mar 28, 2019 at 15:42 | comment | added | chux |
Classic example div_t div()
|
|
| Oct 20, 2017 at 23:25 | comment | added | Peter Cordes |
Oops, right. Well the same thing would apply exactly to struct { int a; _Bool b; }; in C, if the caller wanted to test the boolean, because trivially-copyable C++ structs use the same ABI as C.
|
|
| Oct 20, 2017 at 14:15 | comment | added | Basile Starynkevitch | @PeterCordes: your related things are C++, not C | |
| Oct 20, 2017 at 11:08 | comment | added | Peter Cordes |
Related: bugs.llvm.org/show_bug.cgi?id=34840 std::optional<int> returns the boolean in the top half of rax, so you need a 64-bit mask constant to test it with test. Or you could use bt. But it sucks for the caller and callee compare to using dl, which compilers should do for "private" functions. Also related: libstdc++'s std::optional<T> isn't trivially-copyable even when T is, so it always returns via hidden pointer: stackoverflow.com/questions/46544019/…. (libc++'s is trivially-copyable)
|
|
| Oct 20, 2017 at 11:05 | comment | added | Peter Cordes |
Actually small structs are packed into rdx:rax. So struct foo { int a,b; }; is returned packed into rax (e.g. with shift/or), and has to be unpacked with shift / mov. Here's an example on Godbolt. But x86 can use the low 32 bits of a 64-bit register for 32-bit operations without caring about the high bits, so it's always too bad, but definitely worse than using 2 registers most of the time for 2-member structs.
|
|
| Oct 20, 2017 at 8:40 | history | edited | Basile Starynkevitch | CC BY-SA 3.0 |
added 124 characters in body
|
| Oct 20, 2017 at 8:29 | history | answered | Basile Starynkevitch | CC BY-SA 3.0 |