7 ms·
what's wrong with that?
by everslick 5y ago
what's wrong with that?
- jacquesm 5y agoint increment(a) { return a+1; } void somefunc() { int b = 5; b = increment(b); printf("b now %d\n", b); }
- everslick 5y agothat exact example is given in the document and presented as 1 of 2 possible solutions. I believe, the critique in the parent comment was unwarranted, but I thought I maybe missed something.
- jacquesm 5y agoThis is the only proper way of doing that. Having pointers to variables on input that functions modify is ugly and error prone. C gets a lot better the moment you try to make your functions as pure as you can.
- jcelerier 5y agoAs long as you don't return structs, as the compiler may introduce memcpys here. C doesn't have C++'s RVO, last time I checked many cases that GCC and Clang did optimize in C++ weren't optimized in C.
- tpush 5y agoDo you have an example of that where C++ struct returns are optimized but not C ones?
- jcelerier 5y agoenjoy: https://gcc.godbolt.org/z/7Pn8eqhdK https://gcc.godbolt.org/z/7Pn8eqhdK that's latest GCC, at -O3
- moonchild 5y agoClang does generate good code https://gcc.godbolt.org/z/z781r7Phh https://gcc.godbolt.org/z/z781r7Phh But yes, sadly I think it's still generally advisable to avoid returning large structs by value. Note that this has nothing to do with RVO; as I understand it, RVO is about eliding copy constructors, not actual memory copies, and c has no copy constructors and so gets 'RVO' in all cases.
- pjmlp 5y agoTrue, but still one way I appreciate making C safer is by using poor man's Abstract Data Types with translation units. For the use cases that are too expensive to use functions, macros can be used instead. However that is only if C++ cannot be used at all, otherwise don't bother.
- jacquesm 5y agoThat works, at the expense of possibly hiding bugs in plain sight. Macros are a double edged sword in that sense, you can almost but not quite create a DSL on top of C that is a lot more safe but it has its drawbacks, and you need to be very good at mentally modeling macro expansion to read and debug code like that in order to ensure that it does what it seems to be saying that it will do.
- pjmlp 5y agoAgree, if it is me, I rather use inline functions, but anyway as mentioned only use C when there is no other option.
- wruza 5y agoWhat do you think of T get_t(int how, char **error); int get_val(T *v); One could rewrite these as struct get_t_res {T; char *}; struct get_t_res get_t(int); struct get_val_res {int; T}; struct get_val_res get_val(); But what do you think of it?
- jacquesm 5y agoLess clear. I much prefer for functions to do what's on the tin in the most simple way possible.
- rep_movsd 5y agoShould be `(*a)++` Noob mistake
- wruza 5y ago*a++ doesn’t increment the value pointed to by `a`, it increments `a` itself. The value remains intact.