I am not getting the difference between an integer a
and *(&a)
? I mean *(&a)
returns the value contained in the address of a
and it's the same as a
, no? So why the use of pointers in this case?

- 514
- 4
- 19
-
5Could you provide more context? – personjerry Nov 05 '15 at 05:46
-
The only reason one could possibly write this is to prevent a from being stored exclusivley in a register (since it's address is taken, that is not possible).This has implications when the variable is used without initialization; it makes that less dangerous. Cf. http://stackoverflow.com/a/11965368/3150802. – Peter - Reinstate Monica Nov 05 '15 at 05:55
-
Sure it is, it'll get optimized out. – Blindy Nov 05 '15 at 05:58
4 Answers
What is the difference between an integer
a
and*(&a)
?
No difference. int a;
declares a
as a variable of an int
type. &a
is the address of a
is of type int *
, i.e. pointer type and therefore it can be dereferenced. So, *(&a)
will give the value of a
.

- 104,019
- 25
- 176
- 264
As long as a
is a variable, there's no difference, they're identical.
However, if you use that expression in a macro for instance, it will fail with a compiler error for temporary objects (*&(x+1)
) or literals (*&5
). Perhaps there's a reason for making that distinction in code.

- 65,249
- 10
- 91
- 131
-
*Perhaps there's a reason for making that distinction in code*: What's that? – haccks Nov 05 '15 at 06:19
-
@haccks If the macro evaluates the expression twice you want to prevent it from being used on something that may have side effects. – Peter - Reinstate Monica Nov 05 '15 at 06:34
-
@haccks, I have no idea, but I've seen lots of weird little quirks people use in their libraries. Boost is enough to make your teeth hurt. Besides, this is the only use I can think of for the construct in question. – Blindy Nov 05 '15 at 06:43
Take this as an example,
int a = 1;
int *ptr = &a;
ptr
points to some address in memory, and the address of ptr
itself, is different in memory.
Now, take a look at below drawing,
// *ptr = *(&a)
// Get the adress of `a` and dereference that address.
// So, it gives the value stored at `a`
memory address of a -> 0x7FFF1234
value stored at 0x7FFF1234 = 1
memory address of ptr -> 0x7FFF4321
value stored at 0x7FFF4321 = &a = 0x7FFF1234
+-------+
+------------> 0x7FFF1234 ---->|a = 1 |
| +-------+
| +-----------------+
| | ptr = |
+--*ptr<-------| 0x7FFF1234 [&a] |<--- 0x7FFF4321
+-----------------+
So, there is no difference between both of them, i.e., int a
and *(&a)
are same.

- 5,320
- 1
- 25
- 43
More to the point, you wouldn't normally write *(&a)
, or *&a
. This could arise as a result of macros or something, but you would normally never actually write something like that explicitly. You can take it to extremes: *&*&*&*&*&*&a
works just as well. You can try it for yourself:
#include <stdio.h>
int main()
{
int a = 123;
int b = *&*&*&*&*&*&a;
printf("%d\n", b);
return 0;
}

- 22,815
- 2
- 22
- 41