Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C macros: advantage/intent of apparently useless macro

Tags:

I have some experience in programming in C but I would not dare to call myself proficient. Recently, I encountered the following macro:

#define CONST(x) (x)

I find it typically used in expressions like for instance:

double x, y;
x = CONST(2.0)*y;

Completely baffled by the point of this macro, I extensively researched the advantages/disadvantages and properties of macros but still I can not figure out what the use of this particular macro would be. Am I missing something?

like image 414
Pankrates Avatar asked Jan 31 '13 15:01

Pankrates


People also ask

What are benefits of macros in C?

Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it is used. A function definition occurs only once regardless of how many times it is called.

Should you use macros?

It's a great time saver, and helps reduce mistakes as the macro will simply perform the pre-programmed steps each time so it reduces human error. That said, because macros simply repeat actions it's important that whatever steps you follow are always going to be the same.

Why do macros exist?

Macros are used to make a sequence of computing instructions available to the programmer as a single program statement, making the programming task less tedious and less error-prone. (Thus, they are called "macros" because a "big" block of code can be expanded from a "small" sequence of characters.)

Should macros be used in C++?

Importance of macros in C++ 99.9% of the C++ programs use macros. Unless you are making a basic file you have to write #include, which is a macro that pastes the text contained in a file.


2 Answers

As presented in the question, you are right that the macro does nothing.

This looks like some artificial structure imposed by whoever wrote that code, maybe to make it abundantly clear where the constants are, and be able to search for them? I could see the advantage in having searchable constants, but this is not the best way to achieve that goal.

It's also possible that this was part of some other macro scheme that either never got implemented or was only partially removed.

like image 199
WildCrustacean Avatar answered Sep 28 '22 04:09

WildCrustacean


Some (old) C compilers do not support the const keyword and this macro is most probably a reminiscence of a more elaborate sequence of macros that handled different compilers. Used like in x = CONST(2.0)*y; though makes no sense.

You can check this section from the Autoconf documentation for more details.

EDIT: Another purpose of this macro might be custom preprocessing (for extracting and/or replacing certain constants for example), like Qt Framework's Meta Object Compiler does.

like image 37
npclaudiu Avatar answered Sep 28 '22 04:09

npclaudiu