Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you declare a variable inside a macro?

Tags:

c++

c

Suppose I have a macro defined as this:

#define FOO(x,y) \
do {
  int a,b;
  a = f(x);
  b = g(x);
  y = a+b;
} while (0)

When expanding the macro, does GCC "guarantee" any sort of uniqueness to a,b? I mean in the sense that if I use FOO in the following manner:

int a = 1, b = 2;
FOO(a,b);

After, preprocessing this will be:

int a = 1, b = 2;
do {
  int a,b;
  a = f(a);
  b = g(b);
  b = a+b;
} while (0)

Can/will the compiler distinguish between the a outside the do{} and the a inside the do? What tricks can I use to guarantee any sort of uniqueness (besides making the variables inside have a garbled name that makes it unlikely that someone else will use the same name)?

(Ideally functions would be more useful for this, but my particular circumstance doesn't permit that)

like image 889
R.D. Avatar asked Nov 28 '22 18:11

R.D.


1 Answers

If we consider scoping of variables, it is guaranteed that a,b inside the do..while() will be different from the ones defined outside.

For your case, the a,b defined outside will not exist inside the do..while().

There are lots of things to watch out for when using MACROs.

like image 99
Shamim Hafiz - MSFT Avatar answered Dec 05 '22 02:12

Shamim Hafiz - MSFT