Is there a difference between the two expressions:
(*x)++
and
++(*x)
I can see both of these statements replace the contents of (*x+1) in *x. But are there any differences between them?
(*x)++ evaluates to the value of*x; as a side effect, the value in *x will be incremented by 1.
++(*x) evaluates to the value of *x + 1; as a side effect, the value in *x will be incremented by 1.
Assuming the code:
int a = 5;
int *x = &a;
(*x)++ will evaluate to 5, while ++(*x) will evaluate to 6.
Note that the side effect does not have to be applied immediately after the expression has been evaluated; it only needs to be applied before the next sequence point.
Also note that the parentheses matter for (*x)++; postfix ++ has higher precedence than unary *, so *x++ would be parsed as *(x++); it still evaluates to the value of *x, but as a side effect advances the pointer, rather than increment the thing being pointed to. Prefix ++ and unary * have the same precedence, so they're applied left-to-right; thus ++(*x) and ++*x would have the same result (*x gets incremented, not x).
Let us say the value pointed by x is 10 i:e (*x is 10)
y = (*x)++;
the above statement will be executed as
1. y = *x
2. *x = *x + 1
so y = 10 & *x is 11
y = ++(*x);
the above statement will be executed as
1. *x = *x + 1
2. y = *x
so y = 11 & *x is 11
One increments the values stored in x before it is used (pre), while the other does it after it is used (post).
Also note that ++(*x) is not the same as (*x + 1). The first increments the value and stores it back, the other just increments the value.
One is "pre" and the other is "post". That's the difference. One is evaluated before the the increment (the first option), the other is evaluated after the increment (the second option).
Related
IS there a difference between these pointers? What exactly is happening here for each call.
*p++
(*p)++,
*(p)++
1 and 3 are the same.
Remember that both postfix and unary forms of ++ and -- have a result and a side effect:
The result of x++ is the current value of x - as a side effect, x is incremented by 1 (if x is a pointer, it is incremented to point to the next object in a sequence);
The result of ++x is the current value of x plus 1 - as a side effect, x is incremented by 1 (if x is a pointer, the result is the address of the next object in a sequence, and x is updated to point to the next object in a sequence);
Both forms of -- work the same way, except the value is decremented by 1 - if it's a pointer, then it's set to point to the previous object in a sequence.
When you throw pointer dereferences into the mix, you get the following:
The expression *p++ is parsed as *(p++) (so is *(p)++). The result of *p++ is the current value of *p (the value of the thing p is currently pointing to). As a side effect, p is incremented to point to the next object of the same type in a sequence (IOW, the next element of an array);
The expression (*p)++ is parsed as written. The result of (*p)++ is the current value of *p. As a side effect, *p is incremented by 1. That is, the value of the thing being pointed to is updated, not the pointer.
The expression ++*p is parsed as ++(*p). The result of ++*p is the current value of *p plus 1. As a side effect, *p is incremented by 1.
The expression *++p is parsed as *(++p). The result of *++p is the value of the object following the object p currently points to. As a side effect, p is incremented to point to the next object.
Assume the following declarations:
int a[] = {1, 2, 3, 4};
int *p = a;
After these lines, the value of p is &a[0]. So, given the expression
x = *p++;
the result of *p++ is 1 (the value of the thing p currently points to), which gets assigned to x. The side effect is that p is updated to point to a[1].
Then we execute
x = (*p)++;
The result of (*p)++ is the value of the thing p currently points to (if p points to a[1], then the value is 2), which gets assigned to x. As a side effect, the thing p points to is incremented (if p points to a[1], then the value of a[1] is now 3).
The we execute
x = ++*p;
The result of ++*p is the value of the thing p points to plus 1, and as a result the thing p points to is incremented (if p points to a[1], then the value of a[1] + 1 is 4, which is assigned to x, and the value of a[1] is now 4).
Finally, we execute
x = *++p;
The result of *++p is the value of the object following the object that p currently points to, and p is incremented to point to that object (if p points to a[1], then the value of a[2] (3) is written to x, and p is updated to point to a[2]).
Again, -- works the same way, just in the other direction.
tiny test program.
#include <stdio.h>
int main(void) {
char z[] = "World";
char n[] = "Something";
char *x = "Hello!!";
while(*x) printf("%c", *x++);
printf("\n");
x = z;
while(*x) printf("%c", (*x)++);
printf("\n");
x = n;
while(*x) printf("%c", *(x)++);
printf("\n");
return 0;
}
so the *x++ dereference the pointer, then increments the pointer
(*x)++ - only increments the referenced object.
*(x)++ == *x++
IMO instead of asking try yourself. You will learn something https://ideone.com/bliza0
*source++ will be parsed as *(source++) because of higher precedence of ++ over * operator. It will increment the pointer by 1 and then will dereference the pointer.
To understand the behaviour first let me explain how post increment operator works. When you do
int i = 0;
int j = i++;
then it means that the value of the expression i++ will be the value of the operand i. In this case it will be 0. The value of the i will be incremented as a side-effect. See the quote from the draft
n1570 - §6.5.2.4/2:
The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The value computation of the result is sequenced before the side effect of updating the stored value of the operand.
In case of *source++, compiler will parse it as *(source++). The result of the expression source++ is the value of source. So the current pointer (the address source is pointing to before the side-effect) will be dereferenced and then the side-effect on source will be performed.
(*source)++ will first dereference the pointer and then increment the dereferenced value by 1.
*(source)++ is equivalent to the first case.
I apologies for the wrong answer and leaving the wrong answer with strikes so that future readers will take a lesson if any one come to the same wrong conclusion as I did. Thanks #interjay and #pmg for correcting me out. I am really glad that you guys are part of this community and contributing to this community with your sharp eyes and mind.
What is the difference between a++ and a=a+1 in C if a is a variable.
Tell me the difference between the following assignments;
x=a+1;
x=a++;
I am not able to find a convincing explanation on Google.Please explain the difference clearly and step by step.
a = a+1; calculates the result of a+1 and assigns it to a.
a++; increments a by 1, but evaluates to the previous value of a.
++a; increments a by 1, and evaluates to the new value of a.
a += 1 is identical to ++a;.
So for example:
x = a++; → a will be incremented by 1, and the previous value of a will be assigned to x.
x = ++a; → a will be incremented by 1, and the new value of a will be assigned to x.
x=a+1 just sets the value of x.
x=a++ first sets x to the value of a, and then increments a. a++ is an operation in itself, and you could call it as a single statement to increment a, without assigning it to x whatsoever.
FYI, there is also ++a, which could be used like this:
x=++a. In this case, a is incremented first, and then the incremented value is assigned to x. In either case, the ++ operator modifies a, which is not the case for a+1.
From the C11 Standard (draft):
6.5.2.4 Postfix increment [...] operator[...]
[...]
2 The result of the postfix ++ operator is the value of the operand. As a side effect, the
value of the operand object is incremented (that is, the value 1 of the appropriate type is
added to it).
So
int a = 0;
int x = a++;
results in a being 1 and x being 0.
x = a++ returns the value of a to the variable x first and later it is incremented.
x = a+1 Here a+1 is evaluated and the result is stored in x
3 differences
Return value and side effect
// a is incremented, but its former value is assigned to x
x=a++; //
// a is unchanged. The sum of `a+1`is assigned to x
x=a+1;
Operator precedence. post-fix ++ (aka Suffix increment) is higher precedence than simple addition.
++ only works with integer and non-void* pointer types. +1 works with all scalar type including double.
int a;
x=a++; // valid
x=a+1; // valid
double a;
x=a++; // invalid
x=a+1; // valid
I'm confused in how this code will get executed. Suppose we have
int x=30,*y,*z;
y=&x;
what is the difference between *y++ and ++*y? and also what will be the output of this program?
#include<stdio.h>
int main(){
int x=30,*y,*z;
y=&x;
z=y;
*y++=*z++;
x++;
printf("%d %d %d ",x,y,z);
return 0;
}
The expression x = *y++ is in effects same as:
x = *y;
y = y + 1;
And if expression is just *y++; (without assignment) then its nothing but same as y++;, that is y start pointing to next location after increment.
Second expression ++*y means to increment the value pointed by y that same as: *y = *y + 1; (pointer not incremented)
It will be better clear with answer to your first question:
Suppose your code is:
int x = 30, *y;
int temp;
y = &x;
temp = *y++; //this is same as: temp = *y; y = y + 1;
First *y will be assigned to temp variable; hence temp assigned 30, then value of y increments by one and it start point to next location after location of x (where really no variable is present).
Next case: Suppose your code is:
int x = 30, *y;
int temp;
y = &x;
temp = ++*y; //this is same as *y = *y + 1; temp = *y;
First value of *y increments from 30 to 31 and then 31 is assigned to temp (note: x is now 31).
next part of your question (read comments):
int x = 30, *y, *z;
y = &x; // y ---> x , y points to x
z = y; // z ---> x , z points to x
*y++ = *z++; // *y = *z, y++, z++ , that is
// x = x, y++, z++
x++; // increment x to 31
what is the difference between *y++ and ++*y?
The meaning of an expression in C is characterized by two things: what value it produces and what side effects it produces.
Let's examine the first expression.
Postfix increment is of higher priority than dereferencing, so this is *(y++).
The postfix increment produces a side effect: it changes the value of y to point to a different location. The postfix increment also produces a value: the value that y had before it was incremented. The * operator then dereferences that value to produce an lvalue: that is, something you can use as a variable, either to store to or to fetch from.
I note that the side effect can happen at any point before or after the dereferencing. If you said
q = *y++
then the side effect of the ++ could happen at any point. This could be:
q = *y;
y = y + 1;
or it could be treated as
t = y;
y = y + 1;
q = *t;
Both are perfectly legal. (Except of course that if y is itself an expression with side effects, those side effects must be produced only once. For clarity, I'll make that assumption throughout.)
How about ++*y? That is straightforward: *y produces a variable, the content of the variable is incremented, and the value of the expression is the incremented value. Note that again, the side effect can be produced out-of-order:
q = ++*y
could be treated as:
t = *y + 1;
*y = t;
q = t;
or as
t = *y + 1;
q = t;
*y = t;
Remember, C does not produce very many restrictions on the order in which side effects may happen, so be careful.
what is the difference between *y++ and ++*y?
In case of expression *y++ and *z++; because the postfix version ++ takes precedence over *, the compiler sees this as;
*(y++) = *(z++);
In case of ++*y; compiler sees this as ++(*p) and it will first increment the value of the object it points to ( x in this case) and then return its incremented value.
Summary table for other possibilities;
Expression Meaning
-------------------------------------------------------------------------------------
*y++ or *(y++) Value of expression is *y before increment; increment y latter
(*y)++ Value of expression is *y before increment; increment *t later
*++y or *(++y) Increment y first; value of expression is *y after increment
++*y or ++(*y) Increment *y first; value of expression is *y after increment
EDIT: As pointed out by Eric Lippert in his comment that saying: value of expression is *y before increment, increment y later is misleading, I want to clarify here that the words I used latter and after to emphasize that previous or next value of *y, respectively, will be used in expressions.
Note that, the side-effect can be produced in any order, either side-effect produce first and value assigned latter or value assigned first and side-effect produce latter. For more detail read the answers :-- 1, 2 given by Eric Lippert.
I trust that you understand what the operators ++ and * means when used separately. When used together then operator precedence comes into play. In C++ the ++ operator has a higher precedence than the * operator. So effectively *y++ means *(y++) and ++y* means (++y)*. I hope this helps.
I have a question about these two C statements:
x = y++;
t = *ptr++;
With statement 1, the initial value of y is copied into x then y is incremented.
With statement 2, We look into the value pointed at by *ptr, putting that into variable t, then sometime later increment ptr.
For statement 1, the suffix increment operator has higher precedence than the assignment operator. So shouldn't y be incremented first and then x is assigned to the incremented value of y?
I'm not understanding operator precedence in these situations.
You're mistaken about the meaning of your 2]. Post-increment always yields the value from before the increment, then sometime afterward increments the value.
Therefore, t = *ptr++ is essentially equivalent to:
t = *ptr;
ptr = ptr + 1;
The same applies with your 1] -- the value yielded from y++ is the value of y before the increment. Precedence doesn't change that -- regardless of how much higher or lower the precedence of other operators in the expression, the value it yields will always be the value from before the increment, and the increment will be done sometime afterwards.
Difference between pre-increment and post-increment in C:
Pre-increment and Post-increment are built-in Unary Operators. Unary means: "A function with ONE input". "Operator" means: "a modification is done to the variable".
The increment (++) and decrement (--) builtin Unary operators modify the variable that they are attached to. If you tried to use these Unary Operators against a constant or a literal, you will get an error.
In C, here is a list of all the Built-in Unary operators:
Increment: ++x, x++
Decrement: −−x, x−−
Address: &x
Indirection: *x
Positive: +x
Negative: −x
Ones_complement: ~x
Logical_negation: !x
Sizeof: sizeof x, sizeof(type-name)
Cast: (type-name) cast-expression
These builtin operators are functions in disguise that take the variable input and place the result of the calculation back out into the same variable.
Example of post-increment:
int x = 0; //variable x receives the value 0.
int y = 5; //variable y receives the value 5
x = y++; //variable x receives the value of y which is 5, then y
//is incremented to 6.
//Now x has the value 5 and y has the value 6.
//the ++ to the right of the variable means do the increment after the statement
Example of pre-increment:
int x = 0; //variable x receives the value 0.
int y = 5; //variable y receives the value 5
x = ++y; //variable y is incremented to 6, then variable x receives
//the value of y which is 6.
//Now x has the value 6 and y has the value 6.
//the ++ to the left of the variable means do the increment before the statement
Example of post-decrement:
int x = 0; //variable x receives the value 0.
int y = 5; //variable y receives the value 5
x = y--; //variable x receives the value of y which is 5, then y
//is decremented to 4.
//Now x has the value 5 and y has the value 4.
//the -- to the right of the variable means do the decrement after the statement
Example of pre-decrement:
int x = 0; //variable x receives the value 0.
int y = 5; //variable y receives the value 5
x = --y; //variable y is decremented to 4, then variable x receives
//the value of y which is 4.
//x has the value 4 and y has the value 4.
//the -- to the right of the variable means do the decrement before the statement
int rm=10,vivek=10;
printf("the preincrement value rm++=%d\n",++rmv);//the value is 11
printf("the postincrement value vivek++=%d",vivek++);//the value is 10
The following code confused me a bit:
char * strcpy(char * p, const char * q) {
while (*p++=*q++);
//return
}
This is a stripped down implementation of strcpy function. From this code, we see that pointer p and q are incremented then dereferenced and q is assigned to p until the \0 char has been reached.
I would like someone to explain the first iteration of the while loop.
Because the ++ is after the variables, they aren't incremented until after the expression is evaluated. That's why it's the post-increment operator; the pre-increment is prefixed (++p). *++p would write to the second spot, *p++ writes to the first.
No, the increment happens after the assignment.
If it were *(++p), the pointer p would be incremented and after that assigned.
p++ is post-incrementing the pointer p. So the current value of p is operated upon by the deference operator * before p is incremented.
Your reasoning would've been correct if the while loop was written as follows:
while (*++p=*++q);
In this case the increment would happen before dereferencing.
The expressions x++ and ++x have both a result (value) and a side effect.
The result of the expression x++ is the current value of x. The side effect is that the contents of x are incremented by 1.
The result of the expression ++x is the current value of x plus 1. The side effect is the same as above.
Note that the side effect doesn't have to be applied immediately after the expression is evaluated; it only has to be applied before the next sequence point. For example, given the code
x = 1;
y = 2;
z = ++x + y++;
there's no guarantee that the contents of x will be modified before the expression y++ is evaluated, or even before the result of ++x + y++ is assigned to z (neither the = nor + operators introduce a sequence point). The expression ++x evaluates to 2, but it's possible that the variable x may not contain the value 2 until after z has been assigned.
It's important to remember that the behavior of expressions like x++ + x++ is explicitly undefined by the language standard; there's no (good) way to predict what the result of the expression will be, or what value x will contain after it's been evaluated.
Postfix operators have a higher precedence than unary operators, so expressions like *p++ are parsed as *(p++) (i.e., you're applying the * operator to the result of the expression p++). Again, the result of the expression p++ is the current value of p, so while (*p++=*q++); doesn't skip the first element.
Note that the operand to the autoincrement/decrement operators must be an lvalue (essentially, an expression that refers to a memory location such that the memory can be read or modified). The result of the expression x++ or ++x is not an lvalue, so you can't write things like ++x++ or (x++)++ or ++(++x). You could write something like ++(*p++) (p++ is not an lvalue, but *p++ is), although that would probably get you slapped by anyone reading your code.
The right hand side of the expression (*q++) will be evaluated prior to *p++, and both will only be incremented after the assignment takes place.
Read the statement right to left and remember post-increment (q++ instead of ++q) happens after everything else in the line is resolved.
*q --> dereference q
= --> assign the value
*p --> to p
increment both.
Do this until q p taking q's element = 0 which is when it reaches the null terminator.
The value of q++ is q
The value of ++q is q+1
This is a stripped implementation of strcpy function. From this code, we see that pointer p and q are increamented, than dereferenced and q is assigned to p until \0 char has been reached.
It happens the other way around. The value at *p is set to *q, then both pointers are incremented.
When you have int foo = bar++ the increment happens after foo has been set. To have it happen first you would do int foo = ++bar
The while loop's condition is performing post-increment. Equivalently:
while (true) {
char* old_p = p;
const char* old_q = q;
++p; // or p++;
++q; // or q++;
*old_p = *old_q;
if (*old_p == '\0')
break;
}