1
votes

For example,

int x = 10;
*(&x) = 20;
printf("%d \n",x); // output is 20

According to ISO C11-6.5.3.2 paragraph 4, it says that

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.

Since the operand &x is neither function designator nor object designator (it is a pointer to type int), I expected undefined behaviour but it works just fine! What am I missing?

2
"If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’", the operand clearly has pointer to type.tkausl
why would you think the value &x is an invalid value?Mike
"if it points to an object, the result is an lvalue designating the object." &x points to int, namely x.alk
The operand (&x) points to an object and has a type of pointer to int, therefore the result is an lvalue designating an object of type int, exactly as the paragraph says.PSkocik
Are you by any chance trying to learn C by reading the standard ? If so, I'd recommend you find some other resource. The standard is aimed towards compiler writers who already understand the language pretty well, not beginners.Quentin

2 Answers

5
votes

The operator &x indicates the address of variable x. When you use an asterisk in front of it, this indicates the content at the address of variable x, which is simply x.

The operators * and & neutralize each other, when used like that.

1
votes

Let me parse it for you:

int x = 10;
*(&x) = 20;
  • * == the asterisk operator
  • &x == the operand (of the asterisk operator)

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.

The operand (&x == address of x where x is an int) points to an object of type int.

=> The result is an lvalue designating x (x==the object).

If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’.

The operand has type pointer to int, therefore the result has type int.