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
?
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
.
What @Mysticial saying is correct. Union elements share memory space. and two variables in union have same start address. following is my example program and its output may help you to understand.
#include<stdio.h>
union u{
int x;
int y;
};
union u a;
int main(){
printf("\n %p %p\n",&a.x, &a.y);
return 1;
}
Output:
~$ ./a.out
0x601030 0x601030
Additionally, as @Alon idea, in C++ you have one more kind of variable called reference variable is alias of other variable. you can create like: (you question is taged C, In C you don't have reference variables) see below:
int a = 10;
int &b = a;
+----+----+
| 10 | <--- a = b
+----+----+
2002
if you print &a
and &b
then you will get 2002
same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With