-1

I would like to know what is the advantage of using a macro instead of declaring a function.

For example I found this line in a header file of an USB library for an ATMEL microcontroller:

#define  udd_detach_device()                 ( Clr_bits(UDP->UDP_TXVC, UDP_TXVC_PUON))

Why is it defined like this, and not like a function?

Thank you for your help.

Wheatley
  • 162
  • 1
  • 7
  • 2
    Macro: used for text substitution in source; Function: used to aid in calculating values, setting up data structures, ... you cannot really replace one with the other – pmg Nov 08 '19 at 13:22
  • 2
    Also, functions are called at run-time while macros are expanded (substituted) at compile-time. – Some programmer dude Nov 08 '19 at 13:23
  • 2
    For your specific case, maybe this is a common operation and the writers simply wanted a simple way to write the expansion that doesn't result in the extra run-time overhead of calling another function. – Some programmer dude Nov 08 '19 at 13:24
  • Yes I know that macro are text substition for the compiler, but I wonder what is the advantage (or disadvantage) of doing that instead of declaring a void -> voind function that performs the same operation? – Wheatley Nov 08 '19 at 13:27

1 Answers1

2

All this #define does is replace every textual occurrence of udd_detach_device() in your source with the following text ( Clr_bits(UDP->UDP_TXVC, UDP_TXVC_PUON)).

This is done before your code is compiled, in the so called pre-processing phase.

You should see this C pre-processor (CPP) phase as a text-editing phase in which parts of the code can be replaced or left out. The CPP recognises a limited set of editing commands that all start with #.

Read this Wikipedia page for more background.

meaning-matters
  • 21,929
  • 10
  • 82
  • 142