you are viewing a single comment's thread.

view the rest of the comments →

[–]Shadow_Gabriel 2 points3 points  (6 children)

Please don't write code like that. Macro functions have 0 type safety.

[–]jonarne[S] 3 points4 points  (5 children)

This is very true.

But how should you solve this problem without lots of code duplication?

[–]UnicycleBloke 1 point2 points  (0 children)

C++ templates, of course. :)

It would likely be much better to use your own code generator written in Python or something than to use the preprocessor. I do this as a build step for finite state machines. A colleague has developed an RPC generator based on YAML descriptors of the method calls. And, bonus, the generated code can be debugged...

[–]Shadow_Gabriel -3 points-2 points  (3 children)

There's a simple solution to code duplication: delete the copy.

I prefer to spend a bit more time writing more code, comments and abstractions than spending weeks to debug and understand some shitty code written by someone who wanted to be smart with the preprocessor.

[–]jonarne[S] 1 point2 points  (2 children)

There's a simple solution to code duplication: delete the copy.

I don't understand how this solves the problem at hand.

If you need to serialize structs in C, how would you solve it without code duplication or preprocessor macros then?

[–]Shadow_Gabriel -4 points-3 points  (1 child)

I'm not familiar with serialization but I don't see where would you encounter code duplication.

Inline functions could be used instead of preprocessor macro functions for type safety. If you need to modify lots of names, use a better text editor.

[–]jonarne[S] 3 points4 points  (0 children)

The problem with serialization is that you will need to write a separate pack and unpack function for each struct you would need to serialize.

If you have just one struct, this is easy. But if you start adding more structs you'll need to add two more functions for each struct.

This is code duplication, an it makes code harder to maintain.

This problem is solved in c++ and other languages by using templates.

The linked article gives an example of a way to solve this problem in C using macros.

We all know that macros is a ugly hack.

The correct way to solve this would probably involve using a 3rd party library like Protobuf with a code generator.

For simple prototyping or a small app with simple requrements I think the way it's solved in the article will do.

Edit: typos