conditional operator in C question - c

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

Related

C incrementation and variable declaration

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.

confusion while subtracting and post decrementing at once

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;

While loop with ++variable

Sorry for this easy question but I couldn't find the answer, if I got a while loop that looks like this. Does it calculate before or after the comparison?
a = 0;
while(a++ < 5)
{
....
When it first runs the loop will it look at it as "1 < 5" or "0 < 5". Thanks
Comparison is done BEFORE the increment, but the body of the loop sees the value AFTER icrementation. So in the first run you'll compare 0 < 5, but in the loop a will have the value of 1.
The postfix operator is applied "after". The prefix operator is applied "before". In the case you've provided the first time 'a' is compared it's value will equal 0
Be careful, cause you can get in trouble with these operators if not used with care. Consider a[ix++] = a[ix] + 1; maybe it will do what you want, maybe not ... try it
Just read the other comment ... very good point that a will take on the ++ value insde the loop.
The result of the expression a++ is the current value of a, so the loop will start out as while ( 0 < 5 ).
The result of the expression ++a is the value of a + 1, so if you had written while ( ++a < 5 ), it would start out as while ( 1 < 5 ).
In both cases, a will be incremented by 1 as a side effect. Note that the side effect does not have to be applied immediately after the expression is evaluated; the only guarantee is that it is applied before the next sequence point (in this particular case, the sequence point is at the end of the conditional expression, so the body of the loop will see the updated value of a). So, if you have an expression like
x = a++ * ++b;
it will be evaluated as x = a * (b + 1), but there's no guarantee that a will be incremented before ++b has been evaluated, nor is there any guarantee that either will be incremented before the multiplication and the assignment. The following is one of many acceptable order of operations:
t1 <- b + 1
x <- a * t1
b <- b + 1
a <- a + 1

I am wondering why this code would produce 2

I don't know if anyone could kindly explain this code for me?
unsigned int x = 0;
(x ^= x ) || x++ || ++x || x++;
printf("%d\n", x);
when I compile this on my computer using gcc 4.2, the output is 2.
Originally i thought maybe this behavior is unspecified but then i figure || will have lower precedence over other operators, so shouldn't the answer be 3? Since there are three "++".
Can someone explain? Thanks
(x ^= x) is evaluated and it yields 0, therefore:
(x++) is evaluated and it yields 0, therefore:
(++x) is evaluated and it yields 2, therefore it stops
It all boils down to one rule: || only evaluates its right side if its left side is false.
The issue is that the || operator is short-circuiting. As soon as it finds a true value, it no longer needs to check the remaining || statements; the answer is already known.
(x ^= x) evaluates to 0.
x++ evaluates to 0, then increments x to 1.
++x evaluates to 2 -- true.
The final or statement does not need to be computed. It "short-circuits" and immediately returns true.
The behaviour is well-defined. You are observing the short-circuiting behaviour of ||; the final x++ is never evaluated.
That is short-circuit semantics in action. The first expression x ^= x evaluates to 0, the second evaluates to 0 as well. The third one evaluates to 2, and then the logical expression is short-circuited since its result its already determined to be true.
Of course you shouldn't use such constructs, but let us analyze the expression.
There are 4 expressions combined with shortcut-OR:
a || b || c || d
b, c and d are only evaluated, if a is false, c and d only if b is false too, and d only if all from the before are false.
Ints are evaluated as 0 == false, everything else is not false.
x ^= 0
with x being 0 is 0 again.
x++
is evaluated and later increased, so it evaluates to 0, which invokes expression c, but later x will be increased.
++x
is first incremented, leading to 1, and then evaluated (leading to 1) which is the reason, why d is not evaluated, but the increment of b is pending, so we get 2.
But I'm not sure, whether such behaviour is exactly defined and leads to the same result on all compilers.
Avoid it.
The expressions between the || operators will be evaluated left to right until one is true:
(x ^= x )
Sets all bits in x to 0/off. (false);
x++
Increments x, it's now 1, but still false because this was a post increment.
++x
(pre-)Increments x, which is now 2 and also true, so there is no need for the right hand side of || to be evaluated.

C programming ++ operator

Why does this code always produce x=2?
unsigned int x = 0;
x++ || x++ || x++ || x++ || ........;
printf("%d\n",x);
the 1st x++ changes x to 1 and returns 0
the 2nd x++ changes x to 2 and returns 1
at which point the or short circuits, returns true, and leaves x at 2.
x++ || x++ || x++ || x++ || ........;
First x++ evaluates to 0 first for the conditional check, followed by an increment. So, first condition fails, but x gets incremented to 1.
Now the second x++ gets evaluated, which evaluates to 1 for the conditional check, and x gets incremented to 2. Since expression evaluates to 1 (true), there's no need to go further.
Because of short circuit in boolean expression evaluation and because || is a sequence point in C and C++.
|| short-circuits. Evaluated from left, when a true value is found (non-zero) it stops evaluating, since the expression now is true and never can be false again.
First x++ evaluates to 0 (since it's post-increment), second to 1 which is true, and presto, you're done!
When you're evaluating "a || b || c || d || e || ..." you can stop evaluating at the first non-zero value you find.
The first "x++" evaluates to 0, and increments x to 1, and evaluating the expression continues. The second x++ is evaluated to 1, increments x to 2, and at that point, you need not look at the rest of the OR statement to know that it's going to be true, so you stop.
Because logical OR short-circuits when a true is found.
So the first x++ returns 0 (false) because it is post-increment. (x = 1)
The second x++ returns 1 (true) - short-circuits. (x = 2)
Prints x = 2;
Because of early out evaluation of comparisons.
This is the equivalent of
0++ | 1++
The compiler quits comparing as soon as x==1, then it post increments, making x==2
Because the first "x++ || x++" evaluates to "true" (meaning it is non zero because "0 || 1" is true. Since they are all logical OR operators the rest of the OR operations are ignored.
Mike
The || operator evaluates the left-hand expression, and if it is 0 (false), then it will evaluate the right-hand expression. If the left hand side is not 0, then it will not evaluate the right hand side at all.
In the expression x++ || x++ || x++ || ..., the first x++ is evaluated; it evaluates to 0, and x is incremented to 1. The second x++ is evaluated; it evaluates to 1, and x is incremented to 2. Since the second x++ evaluated to a non-zero value, none of the remaining x++ expressions are evaluated.
trying replacing || with |.--
It is the short circuiting of logical operators.
It's the same reason when you do
if (returns_true() || returns_true()){ }
returns_true will only get called once.

Resources