Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to apply some basic macros to simplify code in a large project?

I've been working on a foundational c++ library for some time now, and there are a variety of ideas I've had that could really simplify the code writing and managing process. One of these is the concept of introducing some macros to help simplify statements that appear very often, but are a bit more complicated than should be necessary.

For example, I've come up with this basic macro to simplify the most common type of for loop:

#define loop(v,n) for(unsigned long v=0; v<n; ++v)

This would enable you to replace those clunky for loops you see so much of:

for (int i = 0; i < max_things; i++)

With something much easier to write, and even slightly more efficient:

loop (i, max_things)

Is it a good idea to use conventions like this? Are there any problems you might run into with different types of compilers? Would it just be too confusing for someone unfamiliar with the macro(s)?

like image 309
Tim Leaf Avatar asked Apr 20 '10 16:04

Tim Leaf


People also ask

What is macro explain with example?

Macro is defined as something that covers a large amount, or is large in size. An example of macro is the study of the key driving aspects of an economy; macro economics. An example of macro is a very close up photograph of an ant; a macro photograph.


2 Answers

IMHO this is generally a bad idea. You are essentially changing well known and understood syntax to something of your own invention. Before long you may find that you have re-invented the language. :)

like image 107
dkackman Avatar answered Oct 24 '22 21:10

dkackman


No, not a good idea.


  int max = 23;
  loop(i, ++max)...

It is, however, a good idea to refactor commonly used code into reusable components and then reuse instead of copy. You should do this through writing functions similar to the standard algorithms like std::find(). For instance:


template < typename Function >
void loop(size_t count, Function f)
{
  for (size_t i = 0; i < count, ++i) f();
}

This is a much safer approach:


int max = 23;
loop(++max, boost::bind(....));
like image 24
Edward Strange Avatar answered Oct 24 '22 23:10

Edward Strange