Search code examples
cmicrochipmicroprocessors

Is this #define equivalent to this variable definition in C?


Consider this #define:

#define msd_buffer              ((volatile char *) MSD_BUFFER_ADDRESS)

and this variable definition:

volatile char *msd_buffer = MSD_BUFFER_ADDRESS;

Are the two definitions of msd_buffer — as variable and as macro — equivalent?


Solution

  • A #define is a macro. It acts as a direct copy-pasta of what you pass into it. So, msd_buffer is not a variable, it is a cast to a volatile char array.

    Assuming example usage like this:

    msd_buffer[160] = 0xFF;
    

    It would be the same as using it as a variable. However, it doesn't have all the features of a variable, such as assignment:

    msd_buffer = NEW_BUFFER_ADDRESS; // invalid!
    

    Or address taking:

    my_func(&msd_buffer); // invalid!
    

    If you understand these drawbacks (and perhaps there are more), then you are on your way to using a macro like this.