Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers with increment and decrement operators

Tags:

c

In general, when the assignment operator is there left operand should be a variable and not an expression but when I am making left side an expression using pointers, the code is not producing any error.

Jdoodle online compiler/C

It should throw an error however successful compilation is there.

https://www.jdoodle.com/c-online-compiler

#include <stdio.h>

int main()
{
    int x = 30, *y, *z;

    y = &x; // Assume address of x is 1000 and integer is 4 byte size */
    z = y;
    *y++ = *z++;
    x++;
    return 0;
}
like image 252
Sukrit Akhauri Avatar asked Feb 16 '26 18:02

Sukrit Akhauri


1 Answers

The left operand of an assignment does not have to be a variable. For example, the following assignments should and do work perfectly fine (and I assume you know that and just misspoke):

array[index] = value;
*ptr = value;

I think what's confusing you about *y++ = *z++; is that you think that it's assigning to the result of an increment operation, which would indeed make no sense. But that's not the precedence of that expression: *y++ is equivalent to *(y++), not (*y)++. So you're dereferencing the result of y++ and then assign a value to that dereferenced memory location, just as if you had written:

int *ptr = y++;
*ptr = *z++;
like image 108
sepp2k Avatar answered Feb 19 '26 07:02

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!