Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suggestions for learning about macros in C

Tags:

c

macros

I have taken an undergrad course in programming Languages which covered C. However not that I have started working in a company in embedded systems, I see a plethora of macros being used regularly in C.

Please share some links from where I can learn more about macros.

I have K&R 2nd Ed, but I think their style is too terse. Something with more examples would be better for me.

like image 230
user714652 Avatar asked Apr 19 '11 06:04

user714652


People also ask

What do you understand by macros in C Explain with examples?

A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;).

How are macros used in C?

In C, the macro is used to define any constant value or any variable with its value in the entire program that will be replaced by this macro name, where macro contains the set of code that will be called when the macro name is used in the program.

What is the advantage of using macros in C language?

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's used. A function definition occurs only once regardless of how many times it's called.

How do you declare a macro in C?

To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.


1 Answers

In all honesty, you should limit your use of macros to very simple definitions nowadays.

In other words, don't waste your time crafting complex functions with macros.

They tended to have three main uses in the past:

  • simple definitions for the pre-compiler to use such as #define USE_DEBUG and #ifdef USE_DEBUG. These are, by and large, stil very valuable in portable code.

  • fast "inline" functions such as #define SQR(x) ((x) * (x)) which are now much more suited to real inline functions. The macro version have a number of problems, one of which is that i = 7; j = SQR(i++); will not necessarily do what you expect.

  • pre-processor enumerations like #define OKAY 0, #define ERR_NOMEM 1 and so on - these are better done as real enumerations - because the macro versions are basic substitutions, you tend not to get the symbols in debugging information.

like image 113
paxdiablo Avatar answered Nov 04 '22 00:11

paxdiablo