Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a simple variable i and *(&i);

I have the following C program:

int main()
{
    int i = 5;
    printf("Simple value of i = %d", i);
    printf("\nPointer value of i = %d", *(&i));
    return 0;
}

Both of the printf() will print the same thing, which is 5. As per my understanding & is being used for address value and * is used to pick the value on that address.

My question is: Why do we need *(&i) if the same thing can be achieved by a simple i variable?

like image 797
gs650x Avatar asked Jan 05 '18 10:01

gs650x


1 Answers

My question is why we need *(&i) if same thing can be achieved with simple i variable?

Well, you don't need it.

The expression *(&i) is equivalent to i.

6.5.3.2 Address and indirection operators says:

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ''pointer to type'', the result has type ''type''. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.102)

And the footnote:

Thus, &*E is equivalent to E (even if E is a null pointer), and &(E1[E2]) to ((E1)+(E2)). [..]

The C standard allows a compiler to transform the code in anyway as long as the observable behaviour (see: 5.1.2.3 Program execution) is same. So the statement:

printf("\nPointer value of i = %d", *(&i));

can be, in theory, transformed into:

printf("\nPointer value of i = %d", i);

by a compiler without violating C standard.

like image 60
P.P Avatar answered Nov 08 '22 16:11

P.P