Farseer Farseer - 1 month ago 9
C Question

Same address of two variables?

How can I declare two different variables (say x and y) that have the same address?

printf("%p\n",&x); /*will be same */
printf("%p\n",&y);


If possible without
union
?

Answer Source

The precise thing you asked for cannot be done using only the standard facilities of the language, but some compilers have extensions that permit it. For instance, with GCC this might do what you want (documentation here).

#define ASMNAME(x) ASMNAME_(__USER_LABEL_PREFIX__, #x)
#define ASMNAME_(x,y) ASMNAME__(x, y)
#define ASMNAME__(x,y) __asm__(#x y)
int x;
extern int y ASMNAME(x);

int main(void)
{
    return !(&x == &y); /* will exit successfully */
}

Note well what effect this has, though: in the object file, there is only one variable, and its name is x. y has only been declared as another name for it in the source code. This may or may not be good enough depending on what you're trying to do.

Note also that the two variables are treated as distinct for optimization purposes. For instance:

#define ASMNAME(x) ASMNAME_(__USER_LABEL_PREFIX__, #x)
#define ASMNAME_(x,y) ASMNAME__(x, y)
#define ASMNAME__(x,y) __asm__(#x y)
int x;
extern int y ASMNAME(x);

#include <stdio.h>

int main(void)
{
   int a, b;
   x = 1;
   a = x;
   y = 2;
   b = x;
   printf("a=%d b=%d x=%d y=%d\n", a, b, x, y); 
   return 0;
}

may well print

a=1 b=1 x=1 y=2

because the store to y is not considered to affect the value of x.