tags:

views:

78

answers:

4
+1  Q: 

Macro return value

Can macro return an object?

#define macro1 {obj1}

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

Thanks.

+5  A: 

A macro triggers a textual substitution during the preprocessing step (part of the seven phases of compilation). Returning a value occurs at runtime. The question doesn't make sense.

dirkgently
+5  A: 

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.

Kornel Kisielewicz
Thanks. So could I use macro1.function in the example above?
Steveng
Yes, but that would be bad practice. There's one situation in which it is used however, I'll add it to the description.
Kornel Kisielewicz
Your example wouldn't work however, because the `obj` is in `{}` braces.
Kornel Kisielewicz
+3  A: 

The macro of your example replaces the text macro1 with {obj1}. It only replaces text with other text; it doesn't know the concept of objects, or classes.

kiamlaluno
A: 

Function macro are not real functions in the sense of C++ function: they are just preprocessing instructions.

Your source file is first read by the preprocessor, the macro are processed (expanded, replaced, etc.) and the resulting source is then given to the compiler.

So macro are not much more than just 'copy paste' of text in your source file. So you can use macro containing a return statement but it will just be replaced in your code.

See also Function-like macros

Cedric H.