开发者

Is a macro with variables always defined with the variable or constants?

If I have a macro like this in a function:

void SomeFunc(int arg1, int arg2)
{
    float value1, value2;
    float range;

//#define MatrixBlock   MyMatrix.block<arg1,arg2>(value1, value2)
//#define BlockRange     MatrixBlock.block<arg2, range>
  #defin开发者_运维百科e MatrixBlock    MyMatrix.block(value1, value2, arg1, arg2)
  #define BlockRange     MatrixBlock.block(value1, value2, 0, range)

    /* My code using the above macros */

    // Are the following lines necessary? What will happen if I don't undefine the macro?
#undef MatrixBlock
#undef BlockRange
}

Will it acquire new arg1 and arg2 values every time or will they be fixed the first time the macro is encountered? Do I need #undef? What happens if I don't have the #undefs


Macros do textual replacement, basically the same as if you would so a search-and-replace in your text editor. The result of that is given to the C compiler to parse and generate code.

The macro doesn't care about what arg1 and arg2 are, it just replaces the string MatrixBlock with the string MyMatrix.block<arg1,arg2>(value1, value2). How the result is then interpreted is up to the compiler.


A Macro is just a text substitution.

In your code you have defined the substitutions but never actioned them. You will need to do something like:

void SomeFunc(int arg1, int arg2) {
    float value1, value2;
    float range;  
#define MatrixBlock MyMatrix.block<arg1,arg2>(value1, value2) 
#define BlockRange   MatrixBlock.block<arg2, range>      

    MatrixBlock; // as if you had written MyMatrix.block<arg1,arg2>(value1, value2); in the code
    BlockRange myRange; // as if you had written MatrixBlock.block<arg2, range> myRange; in the code
/* My code using the above macros */
// Are the following lines necessary? What will happen if I don't undefine the macro? 

#undef MatrixBlock 
#undef BlockRange 
} 

So yes, you will get the current values of arg1, arg2, value1, value2, range every time the function is called. I notice that you are trying to specialise a template with run time values which I don't think will work.

If you don't undef the macros then they will be available to all the code following the defines so some subsequent method could make use of them. If this is in a header file then anything that includes it will have access to these macros.

It is unusual to have defines within a method but not unheard of.


The macros are processed as text substitutions in a separate pass before the compiler sees the code. They know nothing about functions and parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜