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
Related
I know that:
int b = 1, c = 2, d = 3, e = 4;
printf("%d %d %d", ++b, b, b++);
results in undefined behavior. Since
Modifying any object more than once between two sequence points is UB.
Undefined behavior and sequence points
But I don't know if:
int b = 1, c = 2, d = 3, e = 4;
printf("%d", b++ + ++c - --d - e--);
is also UB?
What I think is that increment/decrement operators will evalute first because of the precedence, between them right to left since the associativity . Then arithmetic operators will be evaluated left to right.
Which will just be
(b) + (c + 1) - (d - 1) - (e)
that is, 1 + (2 + 1) - (3 - 1) - (4)
= (2 - 4)
= -2
Is it right?
But I don't know if: ... is also UB?
It is not, but your reasoning about why is fuzzy.
What I think is that increment/decrement operators will evaluate first because of the precedence, between them right to left since the associativity . Then arithmetic operators will be evaluated left to right.
Precedence determines how the result is calculated. It doesn't say anything about the ordering of the side-effects.
There is no equivalent of precedence telling you when the side effects (the stored value of b has been incremented, the stored value of e has been decremented) are observable during the statement. All you know is that the variables have taken their new values before the next statement (ie, by the ;).
So, the reason this is well-defined is that it does not depend on those side-effects.
I deliberately hand-waved the language to avoid getting bogged down, but I should probably clarify:
"during the statement" really means "before the next sequence point"
"before the next statement (... ;)" really means "at the next sequence point"
See Order of evaluation:
There is a sequence point after the evaluation of all function arguments and of the function designator, and before the actual function call.
So really the side-effects are committed before the call to printf, so earlier than the ; at the end of the statement.
There is a gigantic difference between the expressions
b++ + ++c - --d - e--
(which is fine), and
x++ + ++x - --x - x--
(which is rampantly undefined).
It's not using ++ or -- that makes an expression undefined. It's not even using ++ or -- twice in the same expression. No, the problem is when you use ++ or -- to modify a variable inside an expression, and you also try to use the value of that same variable elsewhere in the same expression, and without an intervening sequence point.
Consider the simpler expression
++z + z;
Now, obviously the subexpression ++z will increment z. So the question is, does the + z part use the old or the new value of z? And the answer is that there is no answer, which is why this expression is undefined.
Remember, expressions like ++z do not just mean, "take z's value and add 1". They mean, "take z's value and add 1, and store the result back into z". These expressions have side effects. And the side effects are at the root of the undefinedness issue.
If I have a function such as
f1 (int a)
{
a = a % 2 ? a + 2 : a;
printf(”%c ” , ’a’ + a);
}
and I call f1(0)
What does a%2 as the condition mean?
It checks whether a is even or odd.
a % 2 gives remainder after dividing a by 2, i.e. 0 for even numbers and 1 for odd numbers. And then 0 or 1 is used as condition expression in ternary operator ?: to use either the first expression or the second expression as the final expression result.
int main() {
int x=1;
int a=2;
int b=3;
if(a++>2 && --b<3)
x=5;
printf("%d %d %d",a,b,x);
}
Shouldn't this code return 3 2 5 respectively, instead of 3 3 1?
a++>2
will return false, since 2 is not greater than 2 (remember, a++ means the old value of a will be returned, not the incremented value). Also, ais now worth 3.
Since the && operator is short-circuiting, the --b<3 part will not be evaluated, so b is still worth 3.
The variable x remains unchanged because the conditional was false.
So you do get "3 3 1"
a++>2 is false, and because of short-circuiting, --b<3 is never evaluated. a++>2 is false because a is initially 2, and 2 is not greater than 2. As a side effect, though, a has become 3. Because the condition was false, x is unchanged. Thus the final values of b and x are the same as their initial values, while a has been incremented.
No. Your code explained:
if(a++>2) // a = 2, so 2 > 2? No.
// So the other condition WILL NOT be checked (--b>3), because it's an && condition.
But, a++ increments the 'a', AFTER the expression. So now:
a = 3
b = 3
The code doesn't enter into the if block. So 'x' will never be changed. Then:
a = 3
b = 3
x = 1
If you did:
if(++a>2 ...
The ++a increments BEFORE the expression. So 'a' would be 3 and the if would check '3 > 2'.
The post-increment will be resolved first, then the comparation. That is because of the Operator Precedence Rules.
If you have two operator with different priority, the one with the greater priority will be invoked first, then the other one. If two operator have the same priority, they will be solved according to the corresponding associativity rule.
You can check operators priority and associativity rules in the next link:
http://en.cppreference.com/w/c/language/operator_precedence
I have read in here and in here that postfix(es) are prior to prefix(es).
int a = 5;
int b = 5;
printf("%d\n",a++);
printf("%d\n",++b);
But this code output would be 5,6. how does this make sense then?
What is talked about in your links is operator precedence. That does not affect the working of the post increment. The post increment operator increases the value after the expression in calculated.
Post-increment operator is used to increment the value of variable as
soon as after executing expression completely in which post increment
is used.
What this means is that even if you have a statement like
int i = 0 , j = 5 , k ;
k = ++i + j++ ;
The ++i will be calculated ( i becomes 1 ) and the expression is calculated, and thus k gets the value 6 , and after assigning the value 6 to k, the effect of j++ comes into place and j becomes 6.
Operator precedence determines how operators are grouped, when
different operators appear close by in one expression. For example, '
* ' has higher precedence than ' + '. Thus, the expression a + b * c means to multiply b and c , and then add a to the product (i.e., a +
(b * c) ).
But the precedence does not change the working of the postfix increment. It will increase the value only after the expression is calculated ( that part is independent of it's precedence ) .
I'll give you a simple example ( Hope you know about using pointers )
#include<stdio.h>
int main()
{
int a[] = { 11, 22 };
int x;
int *p = a;
x = *p++;
printf( " *p = %d\n",*p );
printf( " x = %d",x );
}
The output for this is
*p = 22
x = 11
You can refer this ideone link for proof.
Now lets explain that. The ++ has a higher precedence than * , so that code will be same as
x = * ( p++ );
That is, ++ will will make the pointer p point to the next address of the array , but that part is done only after the expression is calculated ( in other words, after the value of *p is assigned to x ) . So after the expression, p will point to the next address, which would have the value 22 while x will still get the value 11.
Hope this makes it clear ( this example might be a bit hard to understand, but it's one of the best to understand this )
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++)