I'm stuck in a question of decrement the code is as follows
#include <stdio.h>
int main()
{
int x = 4, y = 3, z;
z = x-- - y;
printf("%d %d %d\n",x,y,z);
return 0;
}
according to what i know the output should be 4 3 0
the explanation for the value of z according to me is as follows:
first as it's a post decrement so first we'll decrease the value of y from x i.e. 4-3 that's equal to 1 and according to me we'll again decrease 1 from this 1 (or we don't correct me if I'm wrong here) and the output will be 0.
The expression x-- evaluates to the current value of x which is 4. The value of y is then subtracted from this value resulting in 1 which is what is assigned to z.
x is then decremented as a side effect of the postdecrement.
So the output will be 3 3 1.
From 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). 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. With respect to an indeterminately-sequenced function call,
the operation of postfix ++ is a single evaluation. Postfix ++ on an
object with atomic type is a read-modify-write operation with
memory_order_seq_cst memory order semantics.98)
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).
Thus in this statement
z = x-- - y;
there is used the value of the variable x before the decrement that is 4. So 4 - 3 yields 1.
But the object x itself was decremented and after this statement its value becomes equal to 3.
So as result you will get the following output
3 3 1
By the way you may rewrite this statement
z = x-- - y;
like :)
z = x --- y;
Related
I have this question for a practice test in C that I don't understand.
Show the output of the following program
x = y = 3;
y = x++, x++;
printf("x = %d, y = %d\n", x, y);
Answer:
1 x = 5, y = 3
I dont understand what
x++, x++
Does x++ mean to implement the value of x into y then add one to it, but why is there a comma ? Would it just first add the value of x in y, and do x=x+1 twice?
I tried putting it in a compiler, found some struggles.
In this statement:
y = x++, x++;
It contains both the assignment operator and the comma operator as well as the postfix increment operator. Of these the postfix increment operator has the highest precedence followed by the assignment operator, then the comma operator. So the expression parses as this:
(y = (x++)), (x++);
The comma operator first evaluates its left operand for any side effects and discards the value of that operand. There is a sequence point here before it then evaluates its right operand, which means evaluating left side and all side effect are guaranteed to occur before those on the right side.
So let's first look at the left operand of the comma operator:
y = (x++)
The subexpression x++ evaluates to the current value of x and increments x as a side effect. At this point x has the value 3, so y gets assigned the value 3 and x is incremented to 4.
Now for the right side:
x++
Since x currently has the value 4, it is incremented to now contain the value 5.
So at the end x is 5 and y is 3.
There is a wikipedia page explaining the comma operator in C and C++: https://en.wikipedia.org/wiki/Comma_operator
It basically evaluates the two expressions left-to-right and returns the value of the second one.
Here you can see the precedence of operators in c++:
https://en.cppreference.com/w/cpp/language/operator_precedence
The comma operator has the lowest precedence.
In your example.
The first line sets both x and y to 3.
The second line increments x twice: x++, x++.
However, since the assignment operator has higher precedence than the comma operator, y gets the value returned by the first increment.
The statement is evaluated as (y = x++), x++.
The first x++ is executed and x gets the value of 4 and returns 3.
This value is assigned to y: y = x++.
Then, the last x++ is evaluated and x gets the value 5.
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.
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
This question already has answers here:
What is the difference between prefix and postfix operators?
(13 answers)
Closed 8 years ago.
Why is the decrement operator -- not bringing the value down by 1 when executed?
int a = 20;
int c ;
c = a--;
Inspecting the value of c now, it should be 19, yet it comes out as 20. What am I missing?
a-- is Post-Decrement, what you need --a Pre-Decrement. Please read Increment and decrement operators on Wiki
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
int x;
int y;
// Increment operators
x = 1;
y = ++x;
// x is now 2, y is also 2
y = x++;
// x is now 3, y is 2
// Decrement operators
x = 3;
y = x--;
// x is now 2, y is 3
y = --x;
// x is now 1, y is also 1
what you're using is called a postfix operator. It will get executed [decrement the value] after the assignment = operator has finished its execution with the existing value.
To be clear, in case of post decrement, the ..-- operator is evaluated and the decrement is scheduled once the other evaluations including that operand are finished. It means, the existing value of the operand is used in the other evaluation [in =] and then the value is decreased.
If you want, try printing the value of a itself. It will print the decremented value.
EDIT:
If my choice of words in my answer created any confusions, for the reference, from the c99 standard, chapter 6.5.2.4, [emphasis mine]
[For increment] The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented [......]
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).
You are using the post decrement. Post decrement means first use the value in a variable or
anything then decrement the value in the variable. So in this case first value of a will assigned to c. And the decrement is done. You can check printing the value of a.
you should use --a (pre decrement operator), you are using post decrement operator a--
The result of the postfix -- operator is the value of the operand. As a side effect, the
value of the operand object is decremented (that is, the value 1 of the appropriate type is
subtracted to it).
I just have a quick question about the conditional operator. Still a budding programmer here.
I am given x = 1, y = 2, and z = 3.
I want to know, why after this statement:
y += x-- ? z++ : --z;
That y is 5. The values after the statement are x = 0, y = 5, and z = 4.
I know the way the conditional operator works is that it is formatted like this:
variable = condition ? value if true : value if false.
For the condition, y += x-- , how does y become 5? I can only see 2 (2 += 0) and 3 (2 += 1)(then x-- becomes zero) as possibilities. Any help is much appreciated. :)
When it evaluates the condition (x != 0) x is still 1 (that is not 0). So it picks z++. Which is still 3. 2 + 3 = 5. At the end of the day x has become 0 and z has become 4.
Take a look here for details. It's important to remember a simple thing: when you say x ++ the current value of x is used and then it is incremented. When you say ++x it is first incremented and then used.
The Operator ?: has higher precedence than the operator +=. So Your expression is evaluated as
y += (x-- ? z++ : --z);
the value of x-- ? z++ : --z expression is the value of the expression z++ (that is 3) because the value of the expression x-- is 1
Just break it down into a similar if statement:
if (x--)
y += z++;
else
y += --z;
In your case, since x is 1, you'll take the "true" side of this if statement. That means you're adding z++ to y, giving 3 + 2, resulting in 5.
Please don't write code like this.
As a budding programmer just know that you should NEVER write anything like this so that way you can forget about it worrying you!
The reason for this is that post-decrement/increment operator (x++ or x--) does the following:
increment or decrement the variable
return the original value.
So the return value of x-- is 1, indicating true, so the statement z++ is evaluated, returning the original value 3.
Since y = 2, y += 3 is 5.
x-- would mean the expression is evaluated at current value of x and after that x is reduced by 1. Same is the case with Z++. This is the other way around for --z, which means this is evaluated at the new value of z.
So at the time of evaluation x is 1, z is 3. and after the evaluation of expression x becomes 0 and z 4; and y = 2 + 3 = 5
Remember that the increment and decrement operators return different things depending on whether they're placed before or after the name of a variable.
In particular, when x-- is evaluated, it decreases x by 1, but returns the unmodified value of x, which in this case is 1. In C, 1 evaluates to true, so the ternary operator will return z++.
And again, because the ++ operator is placed after the variable, the return value of z++ is the unmodified value of z, which is 3.
Thus, this comes down to y += 3, which results in y being 5.
x-- and z++ decrement and increment after they are used.You end up with the following when the ternary operator is evaluated:
y += (1) ? (3) : (--z);
--z never gets called, the conditional evaluates to true and executes the first option in the ternary operator. After use, x is then decremented, and z is incremented.
It is normal because it first "runs" ternary operator then does decrement as your decrement operator (x--) is postfix, so you got z++ which is 3 so you have 5 in y.
The expression x-- evaluates to the current value of x, which is 1. Thus the result of the conditional expression is z++, which evaluates to 3. 3 gets added to y, for a total of 5.
I think your fundamental issue here is that you're assuming y+= x-- is your condition, when in fact your condition is merely x--. There is a return from the conditional operator which makes y += the result of the conditional operation: x-- ? z++ : --z; is 5. Other comments have the reason why it actually evaluates to 5.
y += (x-- ? z++ : --z); so this is your question and the answer is simple................
As we know that something like X-- Or x++ are called post increment or decrement. So according to the rules of post increment or decrement the expression will be evaluated first and then only increment or decrement will come into action. i.e first evaluate and then increase or decrease.....
NOW lets solve your question:
Y+=X--?Z++:--Z....now it is containing three parts i.e left,middle and right...now the point of consideration is:"if left part is true then it will return middle part, otherwise right side part...and execution always starts from left part as it is the condition part"
Now simplify the statement as:Y+=X?Z:Z;....Now see whether left part is having pre or post increment or decrement.....if post ++/-- is der den first evaluate the simplified statement......den go for ++/--.....
Now left part is having post decrement...so lets first evaluate the expression...i.e
y+=1:3:3 //any non zero value in the condition part is a true condition(i.e 1)
so now our condition is true and it will return the middle part and when the control goes to middle part at that time only x value will be decremented i.e it becomes 0....
Now 2nd simplified statement is Y+=Z. (\\as condition is true and we got middle part,compiler will skip rest of the part i.e right part.)
Now observe whether Z is post ++/-- (or)pre ++/--) ...hahh..its post increment ..so simply first evaluate the simplified statement2 and then increase the value of Z....i.e
Y+=Z =>Y=Y+Z
=>Y=2+3 =>y=5
Now the expression is evaluated i.e Y=5,so now increment the value of Z i.e it become 4
As we know operators checks condition if it is true i.e 1 it executes true statement.
If it is false i.e 0 it executes false statement
Being we are initialising value of x to 1 it executes true statement
As a result it exposes result 5 from true part y=(y+z++)