Home Can I use same variable name in macro
Reply: 1

Can I use same variable name in macro

chan hong Park
1#
chan hong Park Published in 2017-09-13 00:58:52Z

I wrote a code like below.

Test Macro 1 uses a variable which has same name (nCount) from what it is called. And Test Macro 2 uses a different named variable.

I thought the variable of Macro 1 is regarded as different one, because it is packed by square brackets.

But the value of variable in function is change to macro's value. (You can see the result in tracelog result.)

On the other hand, the Macro 2 which uses different named variable is ok.

Could somebody explain why this thing is happening?

=====================Trace Log======================================
[MACRO_1] size = 5 / nCount = 5, (0x2b9d84) 
[MACRO_2] size = 10 / nCount = 5, (0x2b9da4) 

(I thought size value in Macro 1 was also 10, but it was 5)

Source code:

#include <stdlib.h>
#include <stdio.h>

#define TEST_MACRO_1(size)      \
{                               \
    if(0 < size)                \
    {                           \
        int nCount = 5;         \
        printf("[MACRO_1] size = %d / nCount = %d, (0x%x)\n", (int)size, nCount, &nCount);  \
    }                           \
}

#define TEST_MACRO_2(size)      \
{                               \
    if(0 < size)                \
    {                           \
        int nCount2 = 5;        \
        printf("[MACRO_2] size = %d / nCount = %d, (0x%x)\n", (int)size, nCount2, &nCount2);  \      
    }                           \
}

int main()
{
    int nCount = 10;

    TEST_MACRO_1(nCount);  // Macro 1
    TEST_MACRO_2(nCount);  // Macro 2
}
Nisse Engström
2#
Nisse Engström Reply to 2017-09-15 04:06:02Z

Here's what happens:

Macro 1:

When the compiler expands

TEST_MACRO_1(nCount);  // Macro 1

it replaces every instance of size in the macro's replacement list with nCount. This is the result (after adding linebreaks and indenting it for readability):

int nCount = 10;
{
    if(0 < nCount)
    {
        int nCount = 5;
        printf("[MACRO_1] size = %d / nCount = %d, (0x%x)\n", (int)nCount, nCount, &nCount);
    }
}

As you can see, the inner nCount shadows the outer and the code prints 5 instead of 10.

Macro 2:

Similarly, when the compiler expands

TEST_MACRO_2(nCount);  // Macro 2

size is again replaced with nCount and the result becomes:

int nCount = 10;

/* expansion of Macro 1 */

{
    if(0 < nCount)
    {
        int nCount2 = 5;
        printf("[MACRO_2] size = %d / nCount = %d, (0x%x)\n", (int)nCount, nCount2, &nCount2);
    }
}

Here, the inner variable is nCount2, so nothing is being shadowed and the code prints the outer nCount which is 10.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.343006 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO