For example, there is a code:
#include <stdio.h>
int main(void)
{
int n = 54;
int index = 2 * n;
printf("%d\n",index);
n++;
printf("%d\n",index);
return 0;
}
It is clear that the result will be:
108
108
But why doesn't the result depend on the variable change?I mean the following:
int n = 54;
int index = 2 * n;
At this stage, the index value will be 108.
But here:
n++;
The value of n has changed to 55, and the index value should have been 110, but it still stands at 108.
Can this be explained somewhere, for example in the C Standard?
C 2024 3.18 defines object:
region of data storage in the execution environment, the contents of which can represent values
6.5.2 tells us that using an identifier in an expression gives an lvalue (for an object) or a function designator (for a function:
… An identifier primary expression designating an object is an lvalue. An identifier primary expression designating a function is a function designator…
6.5.17.2 tells us that an assignment:
… replaces the value stored in the object designated by the left operand.
6.3.3.1 tells us what happens when we use an lvalue in an expression:
… Except when it is the operand of the
sizeof
operator, or the typeof operators, the unary&
operator, the++
operator, the--
operator, or the left operand of the.
operator or an assignment operator, an lvalue that does not have array type is converted to the value stored in the designated object (and is no longer an lvalue); this is called lvalue conversion…
Finally 6.7.11 tells us about initialization:
… An initializer specifies the initial value stored in an object…
Therefore:
int index = 2 * n;
initializes index
by storing the value of 2 * n
in the data storage of index
. To do this, n
is converted from an lvalue to the value stored in n
, which produces 54. Multiplying this by 2 yields 108, which is stored in index
.n++;
updates the value of n
to 55.printf("%d\n",index);
, the lvalue of index
is converted to the value stored in index
. From above, 108 was stored in index
, so that is the value produced.Nothing in the C standard says that assignment forms any ongoing relationship between the left side of the assignment and the right side or that lvalue conversion does anything other than retrieve a value from memory (i.e., it does not say any sort of calculation based on a relationship is performed; the only action is to retrieve a value from memory).