This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 6 years ago.
Please explain me the outcome of this code.
//code a
when I run this code on my laptop, value of y is 4. And I think, logically value of y should be 5 because by doing x++ it should return 2 without incrementing as it is post increment and then when we add x which now contains an incremented value ie 3. So 2+3 is 5, according to me. But according to my turbo c++ 3.0 answer is 4.
#include <stdio.h>
void main() {
int x = 2,y;
**int y = x++ + x;** // ans 4
printf("y is :%d", y);
}
// code B
When I run this code, the answer is 6. Here turbo c++ 3.0 in ++x is picking up an incremented value of x++, which is the opposite of above mention code. Logically here answer is correct but in the above code it's not.
#include <stdio.h>
void main() {
int x = 2,y;
**int y = x++ + ++x;** //and 6
printf("y is :%d", y);
}
Firstly, assignment operator that is = works from right to left, which means if you write x = 2 + 4 + 1; your compiler starts reading it from rightmost digit that is 1 then it add 4 to it and so on and then it assigns that value to x.
So, in your case statement y = x++ + x; compiler starts seeing it from right that is it first sees x i.e. 2 and then sees x++ i.e. also 2 as it is post increment operator finally it adds them and assigns y as 2 + 2 that is 4.
In the second case, that is y = x++ + ++x;, compiler first looks at ++x and as it is pre increment operator it increases x with one, i.e. x is now 3. After that x++ is seen and as stated above because it is post operator it would be treated as x in this operation and that value is 3 (remember we incremented x by one earlier) and hence, compiler assigns 3 + 3 i.e. 6 to y.
First program where the result is 4
#include <stdio.h>
void main() {
int x = 2,y;
**int y = x++ + x; // x=2, so y=2+2=4
printf("y is :%d", y); // after post increment x=3
}
Since a variable only gets it post incremented value only after the execution of the statement is completed so y=2+2
Second program where the result is 6.
Associativity of ++ operator is "right to left"
void main() {
int x = 2,y;
**int y = x++ + ++x; //Since associativity is left to right so y=3+3=6
printf("y is :%d", y);// after the post increment x=4
}
Here the pre-increment is performed first since because of the associativity rule so y=3+3
Related
This question already has answers here:
What is the difference between prefix and postfix operators?
(13 answers)
Closed 11 months ago.
When I was doing the practice questions today, I found that the outputs of printf("%d\n",x--); and printf("%d\n",x); are the same.
I changed it to printf("%d\n",x++); and found to be the same. I want to know why.
#include<stdio.h>
int main()
{
int x;
scanf_s(" %d", &x);
if (x++ > 5)
printf("%d",x);
else
printf("%d\n",x--);
return 0;
}
You used the post-decrement/-increment operators.
x-- decrements x and returns the original value of x.
x++ increments x and returns the original value of x.
To get the desired behaviour, use the pre-decrement/-increment operators.
--x decrements x and returns the modified x.
++x increments x and returns the modified x.
That's simple and you can understand as well if you know the usage of these 2 kind of operators.
Post Increment/Decrement Operator e.g. a++, a-- etc.
So when we use it in the statement, the current value of the variable will be used and post that its value is incremented by 1.
Just take a look into my comments at end of statements (shows the o/p).
#include<stdio.h>
int main()
{
int x;
scanf_s(" %d", &x); // 10
printf("%d", x++); // 10
printf("%d", x); // 11
return 0;
}
Pre Increment/Decrement Operator, e.g. ++a, --a etc.
So when we use it in the statement, first its value of variable is incremented by 1 & then the incremented value will be used.
#include<stdio.h>
int main()
{
int x;
scanf_s(" %d", &x); // 10
printf("%d", ++x); // 11
printf("%d", x); // 11
return 0;
}
I think, now it's clear to you. For info on usages, just take a look into Usage of Pre/Post Increment & Decrement operators in C.
According to the C Standard (6.5.2.4 Postfix increment and decrement operators)
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)
and
3 The postfix -- operator is analogous to the postfix ++ operator,
except that the value of the operand is decremented (that is, the
value 1 of the appropriate type is subtracted from it).
Consider this pair of calls of printf
int x = 10;
printf( "%d\n", x++ );
printf( "%d\n", x );
The output is
10
11
That is the value of the expression of x++ is the value of its operand that is equal to 10. As a side effect the variable x is increased and in the second call of printf the new value of x after applying the side effect is outputted.
You can imagine this call
printf( "%d\n", x++ );
like
printf( "%d\n", x ), x += 1;
Opposite to postfix increment and decrement operators the values of unary increment (++x) and decrement (--x) operators are values after incrementing and decrementing their operands.
From the C Standard (6.5.3.1 Prefix increment and decrement operators)
2 The value of the operand of the prefix ++ operator is incremented.
The result is the new value of the operand after incrementation.
and
3 The prefix -- operator is analogous to the prefix ++ operator,
except that the value of the operand is decremented.
I'm new to C language and I'm not entirely sure why on Line 4 when post-increment is done the value of x isn't change what I mean is that
x = printf("%d",x++);
The value for x was 12 so the printf would print 12 and then x should be assigned 2 and while ++ was there x should be later changed with 2+1 and on line 6 pre-increment is done so output shouldn't be 124.
Why x on line 4 isn't added?
Please help.
#include <stdio.h>
int main(){
int x = 12;
x = printf("%d", x++);
printf("%d", ++x);
return 0;
}
Make yourself aware of sequence point. From this [emphasis mine]:
There is a sequence point after the evaluation of all function arguments and of the function designator, and before the actual function call.
From this [emphasis mine]:
Increment operators initiate the side-effect of adding the value 1 of appropriate type to the operand. Decrement operators initiate the side-effect of subtracting the value 1 of appropriate type from the operand. As with any other side-effects, these operations complete at or before the next sequence point.
Looks at this statement:
x = printf("%d", x++);
The post increment operator increase the value of operand by 1 but the value of the expression is the operand's original value prior to the increment operation.
So, the value of x passed to printf() will be its original value which is 12 and due to sequence point, before calling printf() the value of x will be incremented by 1. The return value of printf() will be assigned to x which overwrites the last value of x which is the incremented value due to post ++ operator. Hence, after this statement the value of x is 2.
The value for x was 12 so the printf would print 12 and then x should be assigned 2 and while ++ was there x should be later changed with 2+1 and on line 6 pre-increment is done so output shouldn't be 124.
no, the assignment is done after all concerning printf("%d", ++x);, your code is equivalent to that :
#include <stdio.h>
int main(){
int x = 12;
int y = printf("%d", x++);
x = y;
printf("%d", ++x);
return 0;
}
so x = printf("%d", ++x); does :
printf writes 12
then x is incremented to value 13
then x is assigned to the result of printf valuing 2
then you execute printf("%d", ++x); while x values 2 before, so x is incremented before to be given in argument, so 3 is written
and the final print result is 123
PS. As said by #H.S. in an other remark :There is a sequence point after the evaluation of all function arguments (x++ is an argument to printf()) and the pre/post increment/decrement operation complete at or before the next sequence point.
This will work for you:
++x is prefix increment and the x++ is postfix increment, and here is the difference on both of them:
The prefix increment returns the value of a variable after it has been incremented.
On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.
#include <stdio.h>
int main()
{
int x = 12;
x = printf("%d", ++x);
printf("%d", ++x);
return 0;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on that code, and I tried to use x + 1 instead of ++x and the result was infinite loop and zeros were printed on the screen.
this is the code:
#include <stdio.h>
int main(void){
int x;
for(x = 0; x <= 100; x + 1) //instead of ++x
printf("%d\t",x);
return 0;
}
I wondered this action.....why the compiler didn't produce such an error,,,, and what actually happens??!! and is x++ is treated as x += 1 ?!
You need the value of x to change, or your loop will never terminate. When you have only x + 1, then at the end of the iteration, x + 1 is computed, but its resulting value is discarded. The result of the expression is not stored any place. So x will remain zero, and x <= 100 will remain true, and your loop will continue forever.
If you have any of the following:
x = x + 1
x += 1
x++
++x
the value of x itself is incremented. That's what you need.
Although the basic structure of a for loop is like-
for(initialization; condition; increment or decrement)
But in its core part the "condition" part is treated only to control the loop behavior. So, if other two parts are syntactically correct, then compiler won't produce any error.
Since, x+1 is a valid C statement and the value of the x is not changing so it will go to an infinite loop for the condition [x <= 100 => 0 <= 100] being true forever.
Again, x++ or ++x both treated as x = x + 1 when used independently. But, x++ is actually Post-increment operator, while ++x is Pre-increment operator. That means, the with ++x, the value of the x will be incremented first and then assigned to x. Whereas, the current value of x will be used for the entire statement in x++ and then x will be incremented and assigned with new value. Look at the following example-
#include<stdio.h>
void main()
{
int x=5;
/* Post & Pre-Increment used independently */
x++;
printf("x : %d", x);
++x;
printf("\nx : %d", x);
/* Used with printf() statement */
printf("\nPre-increment of x: %d", ++x);
printf("\nPost-increment of x: %d", x++);
printf("\nPost-increment effect on x: %d", x);
}
Output:
x : 6
x : 7
Pre-increment of x: 8
Post-increment of x: 8
Post-increment effect on x: 9
I Hope my explanation have made you understand, if still not you can reply me back.
The expression x + 1 should be x = x + 1 in for loop, so correct:
for(x = 0; x <= 100; x + 1)
^
doesn't increment x
Infinite loop!
as:
for(x = 0; x <= 100; x = x + 1)
or
for(x = 0; x <= 100; x += 1) // or simply x++ or ++x
The compiler didn't produce such an error because x + 1 is a valid expression (but its not what you wants).
So, x += 1, x++ or ++x are not just add one to x but also modify value of x.
Your approach is not perfect because it definitely increases the value of x but when it comes to assignment, it fails. so your statements should cover all your requirements.
try to use
#include <stdio.h>
int main(void){
int x;
for(x = 0; x <= 100; x = x + 1)
printf("%d\t",x);
return 0;
}
or you can use
#include <stdio.h>
int main(void){
int x;
for(x = 0; x <= 100; x++)
printf("%d\t",x);
return 0;
}
Instead of x++ (post increment) you can also use pre increment (++x).
The expression x = x + 1; can also be written as x += 1; which is a shorthand method for assignment embedded with increment. It is not just about incremnent you can also use other operators.
x -= 3;
x *= 2;
I've been thinking about this in terms of incrementing a pointer, but i guess in general now I don't know the semantic difference between these two operations/ operators. For example, my professor said that if you have int a[10] you can't say a++ to point at the next element, but I know from experience that a+1 does work. I asked why and he said something like "a++ is an action and a+1 is an expression". What did he mean by it's an "action"? If anyone could tell me more about this and the inherent difference between the two operations I'd greatly appreciate it. Thank you.
x++ and ++x
The increment operator x++ will modify and usually returns a copy of the old x. On a side note the prefixed ++x will still modify x but will returns the new x.
In fact x++ can be seen as a sort of:
{
int temp = x;
x = x + 1;
return temp;
}
while ++x will be more like:
{
x = x + 1;
return x;
}
x + 1
The x+1 operation will just return the value of the expression and will not modify x. And it can be seen as:
{
return (x + 1);
}
x++ is an action in the sense that it changes x
x+1 does not change x
x++ is a const expression that modifies the value of x (It increases it by 1). If you reference x++, the expression will return the value of x before it is incremented.
The expression ++x will return the value of x after it is incremented.
x + 1 however, is an expression that represents the value of x + 1. It does not modify the value of x.
a++ will translate to a=a+1 which is an action (due to the contained assignment operation)
a+1 is just an expression which refers to a+1 (either in pointer terms or in terms of a number depending upon a's type)
x++ is equivalent to x = x + 1. It is an action in that it is actually changing the value of x.
Every expression returns a result (unless it's void).
x + 1 returns the value of x + 1.
x++ returns the value of x, and as a side effect the value of x is incremented at some point, not necessarily immediately.
This means you can have:
x = x + 1;
but this is illegal:
x = x++;
#include <stdio.h>
int main()
{
int x = 4, y, z;
y = --x;
z = x--;
printf("%d %d %d", x, y, z);
}
Output: 2 3 3
Can anyone explain this?
And what does i =+ j mean (suppose i = 1 and j = 2)?
y = --x means "decrease x by one, then store the result in y"
z = x-- means "save a temp of x. Decrease x by one. Store the temp value in z"
Hence:
x starts at 4.
It gets decreased by 1 (to 3). 3 is stored in y.
x is saved to a temp. x is decreased again (to 2). then the temp (3) is stored in z.
y and z are printed as 3, x is printed as 2.
The postfix decrement operator (x--) returns the value of the variable before it was decremented.
x = 2, because you've decremented it
twice.
y = 3, because you've assigned
it to the value of x after it was
decremented from 4
z = 3, because you've
assigned it to the value of x
before it was decremented from 3.
simple explanation:
--x or ++x : Value will be modified after.
x-- or x++ : Value will be modified before
Detailed explanation:
--x or ++x: pre-decrement/increment: will first do the operation of decrementing or incrementing first, then it will assign x.
x-- or x++: post:decrement/increment: will first assign the value of x and then it will do the operation of decrementing or incrementing after.
lets write your code in a nicer format and go through your code step by step and annotate it to show you visually what happens:
main() {
//We declare the variables x, y and z, only x is given a value of 4.
int x=4,y,z;
//--x will decrement var x by 1 first THEN it will assign the value of x to y.
//so: x = 3, y = 3 and z = nothing yet.
y = --x;
//x-- will assign the value of x to z first, then var x will be decremented by 1 after.
//so: x = 2, y=3 and z = 3
z = x--;
printf ("\n %d %d %d", x,y,z);
}
You have to understand the notions of post-decrement and pre-decrement operator.
Both will decrement your variable, but one of them will return the original value (x--) and one of them will return the decremented value (--x).
Postfix decrement (x--) is different from prefix decrement (--x).
The former return the value x, then decrements it; the latter decrements and then returns the value.
And if you thing how a postfix is written at low level, you'll find that it is a liiiitle slower than the prefix... :)
y = --x;
X is decremented, then Y is assigned with the value of X (3)
z = x--;
Z is assigned with the value of X (3), the X is decremented (2)
Yes:
x = 4
y = pre-decrement x (basically decrement by 1 and then assign, i.e. y = x-1 = 3
x =3
z = post-decrement x (decrement by 1 after assigning the value, i.e. z = x = 3, then x = x - 1
x = 2
So x = 2, y = 3, z = 3, exactly what you saw.
If the operator is a prefix the incrementation happens before the assignment, if the operator is a postfix the incrementation happens after the assignment.
let ** be an increment/decrement operator. **e means apply ** to e and evaluate the result whereas e** means evaluate e and then apply ** to it.
Ergo, if decrementation and evaluation are seperated, the code reads as:
int x=4,y,z;
x-=1;//3
y = x;//3
z = x;//3
x-=1;//2
which gives you the ouput you have ;)
x++ / x-- is called post increment / decrement (value modified after...)
++x / ++x is called pre increment / decrement (value modified before...)
Here is what happens (roughly) in your example :
int x=4,y,z; // declare x=4, y=0, z=0
y = --x; // decrement x then assign it to y (pre decrement) (y=x=3)
z = x--; // assign x to z then decrement x (post decrement) (z=3 and x=2)
printf ("\n %d %d %d", x,y,z); // output 2 3 3
A pre increment/decrement looks like this in pseudocode
read value
increment/decrement value
write value
assign value
and a post increment/decrement looks like this
read value
assign value
increment/decrement value
write value
#include<stdio.h>
main ()
{
int x=4,y,z;
y = --x;
z = x--;
printf ("\n %d %d %d", x,y,z);
}
output 2,3,3.................................first time x=4 fine. y=--x, means value of x is decremented by 1 and stored in y, thus now y=3 and x is also 3. then z=x-- means value of x is stored in z( z=3) and then x is decremented i.e now x=2 but z=3. when u r printing the value, then printf() prints 2 3 3
Talking about what i=+j; means(given i=1 and j=2)
i=+j; is equivalent to i=i+j; so your expression becomes i=1+2 i.e. i=3