int val = 5;
printf("%d",++val++); //gives compilation error : '++' needs l-value
int *p = &val;
printf("%d",++*p++); //no error
Could someone explain these 2 cases? Thanks.
Pointer Airthmetics In C programming language, *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions. * is dereference operator. Precedence of prefix ++ and * is same and both are right to left associative.
In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.
Q: Does *p++ increment p, or what it points to? A: The postfix ++ and -- operators essentially have higher precedence than the prefix unary operators. Therefore, *p++ is equivalent to *(p++); it increments p, and returns the value which p pointed to before p was incremented.
In Pre-Increment, the operator sign (++) comes before the variable. It increments the value of a variable before assigning it to another variable. In Post-Increment, the operator sign (++) comes after the variable. It assigns the value of a variable to another variable and then increments its value.
++val++
is the same as ++(val++)
. Since the result of val++
is not an lvalue, this is illegal. And as Stephen Canon pointed out, if the result of val++
were an lvalue, ++(val++)
would be undefined behavior as there is no sequence point between the ++
s.
++*p++
is the same as ++(*(p++))
. Since the result of *(p++)
is an lvalue, this is legal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With