What are the advantages of using directives and macros?

5

Do policies and macros influence program performance?

    
asked by anonymous 25.02.2016 / 22:30

1 answer

7

They do not influence performance at all. The specific use of some technique with them may even bring some results.

At first there was only the preprocessor to do some things, but today the compilers have constant values of various forms, inline functions, and much of what was needed no longer needs to be used. >

Many times the feature was used to get more performance, but the current compilers allow you to do the same for the language itself, which gives more allowance to do it correctly.

Today's recommendation is to use this as little as possible. This is a feature seen today more as a disadvantage. Still needed by language deficiencies.

It's very easy to make mistakes using policies. There are a lot of rules that need to be followed to get it right. Even if the programmer dominates all - and there are many - it is still not easy to get right all the time. The compiler does not help because they are not part of the language. It is only a decision to exchange or use text without understanding what is in the code, without scope, without context. It is very easy to imagine that you are doing one thing and doing another. The mechanism is very rudimentary.

An obvious example of a problem occurs in macros:

#define MAX(x,y) (x) > (y) ? (x) : (y)

Well done, you followed the recommended rules. Here's how it works:

int x = MAX(y++, 1);

What is transformed like this:

int x = (y++) > (1) ? (y++) : (1);

Have you realized that you will not produce the result you want? It's full of such traps, even in more innocent situations. And there are many situations that are less innocent than these.

It has tricks to avoid problems. But when you need to fix tricks, the resource is usually wrong.

I will not even mention the difficulty of debug code like this.

Some directives serve to facilitate the construction and organization of the code. Others help in complex constructions allowing flexibility and reuse of code.

Overall this is it. Some specific directives may have more specific advantages. Obviously, #include and #ifdef are still more useful, but they do not directly influence performance. What you do with them can influence performance since you can decide on a better alternative for a given circumstance. It may fail to include a required code in a particular build , so less code helps keep the cache only with what is needed and also avoids a run-time decision.

There are cases that it's best to use anyway.

I do not give a fuller answer because it gets too broad. Each directive has its peculiarity. More specific questions fit.

In C ++ usage is less advisable.

    
25.02.2016 / 23:03