Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Whats the difference between #define and const? Why is the preprocessor frowned upon?

0
Posted

Whats the difference between #define and const? Why is the preprocessor frowned upon?

0

There are a few problems with #define in C and C++, whether the macro is being used as a named constant or as a function-like entity. Among them include: • The preprocessor is effectively a separate language from C or C++, and so at some level the compiler really knows nothing about what happened. In effect, the text substitutions that occur happen before the so-called compiler proper phase is invoked. • Macros have their own scopes. • Macros can produce unplanned for side-effects. • Macros have no type, they are “just text”. • You cannot take the address of a macro. • The debugger, error messages, etc. usually know nothing about macros. Therefore, it’s common that the preprocessor should be avoided for some things. However, there are some alternatives to macros that are often superior and they include: • consts, which are types • enums, which allow distinct related “sets” of constants • inline functions, which obey C++ (and now C99) function semantics • templates, in C++ Of course, th

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123