简体   繁体   中英

Macro return value

Can macro return an object?

#define macro1 {obj1}

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

Thanks.

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.

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.

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.

You can always see what does the compiler do when you define a macro(and call it).The code of the macro is simply replaced (just like copy paste).
compile with gcc -E. For example for this code

#define macro1 {obj1}

int main() {
int obj1;
macro1
}

On compiling with gcc -E example.c i get the following output

# 1 "macro.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "macro.c"



int main() {
int obj1;
{obj1} //here your call gets expanded
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM