From: René Scharfe Date: Tue, 31 Jan 2017 21:02:54 GMT Subject: Re: [PATCH 1/5] add SWAP macro Message-ID: <676ed19c-0c4e-341e-ba30-1f4a23440088@web.de> In-Reply-To: Am 31.01.2017 um 13:13 schrieb Johannes Schindelin: > Hi René, > > On Mon, 30 Jan 2017, René Scharfe wrote: > >> Am 30.01.2017 um 21:48 schrieb Johannes Schindelin: >> >>> The commit you quoted embarrasses me, and I have no excuse for it. I >>> would love to see that myswap() ugliness fixed by replacing it with a >>> construct that is simpler, and generates good code even without any >>> smart compiler. >> >> I don't see a way to do that without adding a type parameter. > > Exactly. And you know what? I would be very okay with that type parameter. > > Coccinelle [*1*] should be able to cope with that, too, mehtinks. Yes, a semantic patch can turn the type of the temporary variable into a macro parameter. Programmers would have to type the type, though, making the macro only half as good. > It would be trivially "optimized" out of the box, even when compiling with > Tiny C or in debug mode. Such a compiler is already slowed down by memset(3) calls for initializing objects and lack of other optimizations. I doubt a few more memcpy(3) calls would make that much of a difference. NB: git as compiled with TCC fails several tests, alas. Builds wickedly fast, though. > And it would even allow things like this: > > #define SIMPLE_SWAP(T, a, b) do { T tmp_ = a; a = b; b = tmp_; } while (0) > ... > uint32_t large; > char nybble; > > ... > > if (!(large & ~0xf)) { > SIMPLE_SWAP(char, nybble, large); > ... > } > > i.e. mixing types, when possible. > > And while I do not necessarily expect that we need anything like this > anytime soon, merely the fact that it allows for this flexibility, while > being very readable at the same time, would make it a pretty good design > in my book. Such a skinny macro which only hides repetition is kind of attractive due to its simplicity; I can't say the same about the mixed type example above, though. The fat version isn't that bad either even without inlining, includes a few safety checks and doesn't require us to tell the compiler something it already knows very well. I'd rather let the machine do the work. René