Search code examples
c++macros

Macro return value


Can macro return an object?

#define macro1 {obj1}

Since macro is text substitution, could I use macro like macro1.function1()?

Thanks.


Solution

  • A macro never returns anything. A macro returns textual representation of code that will be pasted into the place of the program where it is used before compilation.

    Read about the C Preprocessor.

    So:

    #define macro1 {obj1}
    
    int main() {
      macro1
    }
    

    ... will be compiled as if you wrote

    int main() {
      {obj1}
    }
    

    It's just textual substitution, that can optionally take a parameter.


    If you're using GCC you can take a look at what the program will look like after preprocessing, using the cpp tool:

    # cpp myprog.cpp myprog.cpp_out
    

    Generally mixing macro's with objects is bad practice, use templates instead.


    One known usage of macro's in terms of objects is using them to access singletons (however that isn't such a nice idea in general):

    #define LOGGER Logger::getLogger()
    
    ...
    
    LOGGER->log("blah");
    

    You could also use the preprocessor to choose at compile time the object you want to use:

    #ifdef DEBUG
    #  define LOGGER DebugLogger
    #else
    #  define LOGGER Logger
    #end
    
    // assuming that DebugLogger and Logger are objects not types
    LOGGER.log("blah");
    

    ... but the forementioned templates do that better.