Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of ++val++ and ++*p++ in C

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.

like image 542
understack Avatar asked Sep 07 '10 15:09

understack


People also ask

What does * p ++ do in C?

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.

What is ++ i and i ++ in C?

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.

What does * p ++ do * increments p increments value pointed by p error None?

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.

How does pre increment and Post increment work?

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.


1 Answers

++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.

like image 108
sepp2k Avatar answered Oct 22 '22 20:10

sepp2k