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;
}
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 recently learnt about undefined behaviour in C, but this particular code was used in a site as an example for 'comma as an operator', and while I understand how y = x++ in line 2, I dont understand in what order the sub expressions in line 2 are evaluated. I think it is undefined behaviour, but I'm not sure,because the site didn't mention anything as such.
int main()
{
int x = 10, y;
y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);
printf("y = %d\n", y);
printf("x = %d\n", x);
return 0;
}
Output:
x = 11
x = 12
y = 12
x = 13
It is not undefined behaviour.
You first increase x to 11, the print it, then increase it to 12 and print it, then increase it after evaluation, so x will be 13 and the whole expression will evaluate to 12.
This is caused due to the comma operator in C being a sequence point, which means it is guaranteed all side effects of previous evaluations will have been performed, and no side effect from subsequent evaluations have yet been performed.
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
main(){
int x = 256, y = 4;
printf("%d\n\n", x++ + ++y); //output = 261
printf("%d\n\n", x); // output = 257
printf("%d", y); // output = 5
}
Is the final answer 261, because 256 -> 257 (post operator) and 5 -> 5 (pre operator) cause 256 + 5 = 261?
Given:
int x = 256, y = 4;
printf("%d\n\n", x++ + ++y);
In short: The x++ returns the value 256 and then increments x to 257. The ++y increments y to 5 and returns the value 5. The addition, therefore, adds 256 and 5 yielding 261.
Long windedly: The x++ evaluates to the current value of x which is 256 and schedules an increment of x to 257. Similarly ++y schedules the increment of y to 5 and evaluates to the incremented value 5. The addition, therefore, adds 256 and 5 yielding 261. The order in which the terms involving x and y are evaluated is not defined, but both have to be evaluated before the addition (though the increments may not be complete when the addition is evaluated). Because there is a 'sequence point' when the arguments (and the expression denoting the function) have been evaluated but before the function is called, the increments must be complete when printf() is called.
The next two statements print x and y as 257 and 5.
Note that those two printf() operations could be combined into one. Neither could be combined with the first without invoking undefined behaviour. (See Multiple increments and undefined behaviour for more information on this topic.)
So, allowing for the fact that I would not express it quite the way you wrote it, you seem to have the correct explanation.
Also, Standard C has required a return type on all functions for over 15 years now (since C99 was standardized). You should write:
int main(void)
for a main() function that takes no arguments. (See What should main() return in C and C++? for the full details.)
Note that this question only invokes fully defined behaviour (at least, in the printf() statements). It is not asking about multiple increments on a single variable between sequence points.
It will show UNSPECIFIED behavior
In your case, we can't tell whether x++ will be evaluated first or ++y will be evaluated first. It is compiler dependent.
So don't use expressions involving a combination of post-increment or pre-increment operators in C or C++.
For more information refer to the link:
https://www.quora.com/What-does-an-expression-involving-multiple-post-pre-decrement-increment-operators-evaluate-to-in-C-and-C++#
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