Why ++ (* p) does not give the required l-value error?

#include <stdio.h>
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    int *p = arr;
    ++*p;
    p += 2;
    printf("%d", *p);
    return 0;
}

Why this code does not give any compile-time error, my doubt ++*pis evaluated as ++(*p)it *pwill be a constant value 1when we do ++(1), which is not l-value , why does the compiler not give an error?

+4
source share
5 answers

*p will be a constant value [...]

No, this is the same as arr[0].

So,

++(*p);

coincides with

++(p[0]);

coincides with

++(arr[0]);

which is an absolutely correct statement.

+11
source

*p will be a constant value

, . *p a[0], int *p = arr;. a[0] , , *p .

:

++(*p);

:

++(a[0]);

, .

, ++(*p), , :

  • *p , l-.
  • (*p), l- .
  • ++(*p) pre-increment l-, , .
+3

, . lvalue, . :

* . , - ; object, - lvalue, . " ", "".

(C2011, 6.5.3.2/4, )

Unary *, , , , . & sizeof .

+3

++(*p) l-value?

The dereference operator on a pointer gives the value l. Consequently, *pa lvalue and uses the pre-increment operator on it.

+2
source

Just remember both operators you use:

++*p; // increments the value pointed by *p at that time `a[0]` by 1
p += 2; // increments the address p is storing by 2

And the reason the l-value error is not required is because in your statement:

++*p; // *p is not a constant, it is same as a[0]
+1
source

Source: https://habr.com/ru/post/1685787/


All Articles