behavior while loop in c programming - c

output in this case is 1
int main() {
int i = 500;
while( (i++) != 0 );
printf("%d\n", i);
return;
}
output in this case is 0
int main() {
int i = 500;
while( (i=i+1) != 0 );
printf("%d\n", i);
return;
}
I'm Not sure why get this different output in every case I mean why 1 in first case and 0 at second case

For starters the both programs have undefined behavior. Instead of declaring the variable i as having the signed integer type int you should declare it as having the unsigned integer type unsigned int to make the programs correct.
This while loop
while( (i++) != 0 );
stops its iterations when the expression i++ is equal to 0. So when the variable i is equal to 0 the loop stops. But due to the postfix increment operator its value is incremented and becomes equal to 1.
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).
This while loop
while( (i=i+1) != 0 );
also stops its iterations when i is equal to 0 after the assignment i = i + 1.

Related

Is formatted output equivalent? [duplicate]

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.

Evaluation order in ternary operator with increments

#define MAX(a,b) ((a)>(b) ? (a) : (b))
int main(void) {
int a=2;
int b=3;
int c = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
printf("\na= %d", a);// a=3
printf("\nb= %d", b);//b=5
printf("\nc= %d", c);//c=4
a=3;
b=2;
cc = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
printf("\na= %d", a); // a=5
printf("\nb= %d", b); //b=3
printf("\nc= %d", c); //c=4
return 0;
}
I would like to know why c is not evaluating to 5.
It appears to me the evaluation order should be:
First both a and be get incremented in (a++)>(b++)
If for example the first one is greater, the ternary operator in
c=((a++)>(b++) ? (a++) : (b++)), goes to (a++), so a
increments again.
The result of the ternary expression, which is a twice-increment,
should be assigned to c, then c should have the greater value
twice-incremented, that is 5. However, I am getting 4. I suspect the
greater value's second increment is happening at the end, but I can't
explain why, since the parentheses seem to indicate that the
assignment comes at the end.
Any idea?
The postfix ++ operator has a result and a side effect. The result of a++ is the value of a before the increment - given
int a = 1;
int x = a++;
the value of x will be 1 and the value of a will be 2. Note that the side effect of adding 1 to a does not have to be applied immediately after evaluation - it only has to be applied before the next sequence point.
So, looking at
((a++) > (b++)) ? (a++) : (b++)
The ?: operator forces left-to-right evaluation, so the first thing that happens is that (a++) > (b++) is evaluated1. Since a is initially 2 and b is initially 3, the result of the expression is false (0). The ? operator introduces a sequence point, so the side effects to a and b are applied and a is now 3 and b is now 4.
Since the result of the condition expression was 0, we evaluate b++. Same thing, the result of the expression is the current value of b (4), and that value gets assigned to c. The side effect to b is applied at some point, and by the time everything's finished, a is 3, b is 5, and c is 4.
Although within that expression either a++ or b++ may be evaluated first, since the > operator doesn't force left-to-right evaluation.
Let's consider for example this declaration
int c = MAX(a++,b++);
after the macro substitution there will be
int c = (( a++) >( b++ ) ? (a++) : (b++));
The variables a and b are initialized like
int a=2;
int b=3;
As a is less than b then the third expression (b++) will be evaluated as a result of the conditional operator. In the first expression ( a++) >( b++ ) a and b were incremented. There is a sequence point after the evaluation of the first expression.
So a will be set to 3, b will be set to 4.
As it was already said the value of the conditional operator is the value of the third expression (b++) where there is used the post-increment. The value of the post-increment operator is the value of its operand before incrementing.
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).
So the value of the conditional operator is 4. This value will be assigned to the variable c. But as a side effect the value of b will be incremented.
Thus after this declaration a will be equal to 3, b will be equal to 5 and c will be equal to 4.
For clarity this declaration
int c = (( a++) >( b++ ) ? (a++) : (b++));
in fact can be rewritten in the logically equivalent way.
int result = a > b;
++a;
++b;
int c;
if ( result != 0 )
{
c = a++;
}
else
{
c = b++;
}
For a++ it's equivalent as saying
int temp = a;
a = a + 1;
return temp;
so in the case of a=2, b=3, we can go to the condition (a++)>(b++) and we can have a rewritten as
int temp1 = a;
a = a + 1;
return temp1;
and b rewritten as
int temp2 = b;
b = b + 1;
return temp2;
now since it's only a conditional statement, we're really just evaluating the old values of a and b before the increment which is temp1 = 2 and temp2 = 3 while at the same time a and b values have changed a = 3, b = 4. Since temp1 < temp2 from the old value, we go to the false clause of the ternary operator (b++) and do the same thing as we did before
int temp3 = b;
b = b + 1;
return temp3;
so now b is 5 while the returned temp3 is the previous value of b which is 4. Hope this helps!

What will be the possible output?

I code from a long time but I was never asked questions like this before.
main()
{
int a=5, b, c;
b=a=15;
c=a<15;
printf("%d %d",a,c);
}
What will be the values of a and c? How do we interpret '<' or '>' ?
The < operator yields 0 or 1 of type int.
It yields 1 if its left operand is less than its right operand, 0 otherwise.
In your case the left operand has the value a or 15; the right operand has the value 15. So the operator yields the value 0.
Then that 0 is assigned to c.
Your statement with extra whitespace, parenthesis, and a comment can be written as
c = (a < 15); // assign 0 or 1 to c
main()
{
int a=5, b, c;
b=a=15; // a = 15
c=a<15; // a is not < 15, a is 15, so c is 0
printf("%d %d",a,c);
}
First of all, the result of this code is undefined, since you do not supply a function prototype for printf
Second of all, using main() is further undefined since a function needs a return type and main() in particular needs to be int return type (handling of other implementations is implementation-defined.
Now assuming you correct your code to:
#include <stdio.h>
int main(void)
{
int a=5, b, c;
b=a=15;
c=a<15;
printf("%d %d",a,c);
return 0;
}
Then the output for c is 0.
This is because the < operator returns int type 0 or 1 based on if the comparison is true.

Postfix before prefix?

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 )

OR and AND operation in C

I have a doubt in the program below.
int main()
{
int i = -3,j = 2, k = 0,m;
m = ++i || ++j && ++k;
printf("%d %d %d %d\n", i, j, k, m);
return 0;
}
I get the output as -2 2 0 1.
In OR operation if 1st value is true then it won't evaluate the 2nd one so i = -2 and j =2.
Then comes the AND operation . It will check for both the value to be true.So if k = 1 then m = 1.
So the output should be -2 2 1 1. I run and check and got output as -2 2 0 1 but I could not understand how.
You used a short circuit or. Since ++i evaluates to -2, which is not 0, it short circuits and doesn't evaluate the rest of the expression. As a result, neither j or k get incremented.
Also note that the short circuit operators, || and &&, are left associative and that || is higher precedence than &&. As a result, the || gets evaluated first, and early outs if the left hand side evaluates to true, while && early outs if the left hand side evaluates to false.
EDIT: Fixed a mistake with explaining the precedence.
Nothing after the || is evaluated, since the result of the expression ++i is nonzero.

Resources