Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any good uses of macros? [closed]

Tags:

c++

macros

As far as I know, macros rearrange the program text before the compiler even sees it properly, thus potentially causing problems. I hardly ever see them in C++ code, mostly in C.

The only good use I know of, is inclusion guards (#ifndef).

Is there anything else that needs to be done with macros and cannot be implemented in a cleaner way?

like image 728
Oleksiy Avatar asked Aug 22 '13 07:08

Oleksiy


People also ask

Can macro run on closed workbook?

You can cause Excel to run a macro automatically whenever a particular workbook is closed. For instance, when the workbook is closed you might want to run a macro that asks the users if they want to perform some task, such as saving the day's data to another file.

Should macros be enabled or disabled?

Enable all macros (not recommended, potentially dangerous code can run) All macros run without confirmation. This setting makes your computer vulnerable to malicious code. In Excel this option is Enable VBA macros (not recommended, potentially dangerous code can run) and it only applies to VBA macros.

Why macros Cannot be undone?

When we run a macro, we cannot undo the macro's actions using the usual Ctrl + Z shortcut. Running a macro removes the list of actions stored in Undo, meaning that it is not possible to undo a macro.

What can macros be used for?

If you have tasks in Microsoft Excel that you do repeatedly, you can record a macro to automate those tasks. A macro is an action or a set of actions that you can run as many times as you want. When you create a macro, you are recording your mouse clicks and keystrokes.


2 Answers

Logging and Exception.

A macro allows you to effortlessly capture __FILE__, __LINE__ and __func__. Oh sure you could write them manually each time, but frankly this is tedious and error prone (both __FILE__ and __func__ are C-string so you risk mixing them up).

like image 103
Matthieu M. Avatar answered Nov 03 '22 01:11

Matthieu M.


Prior to C++11, you would usually define static_assert as a macro (a typedef that would be invalid if the condition is false), so it can be available from anywhere (namespace level, or function level) and still not be ambiguous (e.g. by using a line number).

The Boost.Preprocessor library is another good example of using macros to reduce the amount of highly redundant code, and another one that is less relevant with variadic templates.

Furthermore macros are widely used to "talk" to the compiler, e.g. checking what compiler you are running on, what version of the compiler, whether C++11 support is available, etc.

like image 42
nijansen Avatar answered Nov 03 '22 01:11

nijansen