Yet more C abuse

Mar 12, 2012 18:52


In two recent posts here, I've suggested moderately evil things to do with the C preprocessor, both on the same theme of defining a macro that can be used like a loop keyword by following its invocation with a statement or block of your choice.

Last week some further thoughts on the subject occurred to me, which were rather more comprehensive and ( Read more... )

Leave a comment

Comments 5

gerald_duck March 12 2012, 22:20:09 UTC
You mention C++, but surely these shenanigans (fascinating in their twistedness though they may be) belong entirely in the land of C?

In the first place, C++ entirely solves the problem of tidying away resources that go out of scope in a rather more thorough way. And, for that matter, iterators allow non-standard behaviours to be packaged in a for-loop-friendly way. (Even more friendly for C++11's range-based for loops.)

In the second, the combination of exceptions and C++'s somewhat necessary prohibition on jumping past a non-trivial constructor or destructor invocation make the idiom unusable in some cases and dangerous in others.

Reply

simont March 12 2012, 23:38:35 UTC
I mention C++ mostly because there exists at least one compiler which hasn't yet got round to supporting C99 - but that compiler does support C++. So if you're prepared to write code in the common subset of C99 and C++ (which mostly just means adding a few explicit casts from void *), then you can do this sort of thing even when one of the compilers you have to support is that one.

It's true, of course, that if you're writing a program that's actually allowed to use C++ features then you probably want to be doing an entirely different set of horrifying language abuses :-)

Reply


andrewducker March 13 2012, 08:32:24 UTC

kehoea April 2 2012, 08:38:47 UTC
We have a good number of macros that might benefit from this in XEmacs, most of them here. (Not the sort of code your average C programmer is that comfortable with, I admit.) Other things are more of a priority at the moment, but I'll bookmark your paper. Thanks!

Reply

simont April 2 2012, 09:18:06 UTC
Yes, I see what you mean! Though it looks to me as if most of those loops fit reasonably well into a for statement, with the only annoying part being the need to declare some variables up front. I don't know what XEmacs's portability requirements are, but if they include C89 then you might find that my trickery doesn't benefit you after all due to the one extra-C89 feature (bringing declarations into scope via for initialisers) not being available to you.

Reply


Leave a comment

Up