Products > Programming

Oh, C3!

<< < (13/13)

Doesn't look too nice, but isn't the alternative copy-pasting and search/replace the whole function? Possibly tens of times? That's just disastrous. Generic programming is needed. In C, that's using preprocessor. In C++, either preprocessor or template system. Generic programming never looks as simple as non-generic, no matter how well designed the language is. It's still super useful.


--- Quote ---but isn't the alternative copy-pasting and search/replace the whole function?
--- End quote ---

No idea - I gave up trying to figure out what it all means :)

"Obvious" tips to help with macros.

First, document your macros as soon as they are non-trivial. Funnily enough, I've seen A LOT of code in which the C code itself was heavily commented, but macros, almost NEVER.

Then, as I suggested earlier, if you want to be sure of your macros (or someone else's) and you have doubts, just TEST them.

Just because they are macros doesn't mean they are out of scope for testing.

Testing is not difficult.
Write test files that include the macros you want to test (ideally your macros sit in header files so just include the corresponding header files), and a bunch of test cases. It doesn't have to be C code at all. Just a series of macro invocations. Write the expected output in separate files.

Run the preprocessor on these test files and compare the outputs with your expected outputs with diff. All this can be fully automated.

I think the issue with stuff like ## is the levels of redirection. We can keep in mind up to 7 levels (if we're good - most people aren't) and a #define is already one level. So you can sit and work it out and even write test cases and know what it does, but then trying to apply that in realtime to what you're looking at is like speaking Spanish while reading Mandarin. And, as I note, the usual tools that let you find, say, a function definition and its associated comments, don't work with this type of macro so you can't easily find any comment either.


--- Quote from: SiliconWizard on April 21, 2023, 08:08:33 pm ---The problem is that it's a half-baked solution: outside of cryptic constructs like the Duff's device, using fallthrough in switch-case in C was mostly meant to emulate the possibility of having cases for multiple values instead of just one. That was much better addressed even in Pascal (if I remember it right) using ranges.

--- End quote ---
FTR, Standard Pascal has case label lists e.g.

case ch of
  'a', 'e', 'i', 'o', 'u': chtype := vowel;

This was extended in Modula-2 to include case label lists and subranges e.g.

  'a', 'e', 'i', 'o', 'u': type := vowel |
  '0'..'9': type := digit |


[0] Message Index

[*] Previous page

There was an error while thanking
Go to full version
Powered by SMFPacks Advanced Attachments Uploader Mod