Please do help me with explaining the output of my code. Currently I'm an amateur in C. If i++ and i=i+1 are the same things then why such difference in output?
#include <stdio.h>
void main()
{
int i=0;
printf("%d %d %d \n",i++,i,i++);
int j=0;
printf("%d %d %d \n",j=j+1,j,j=j+1);
return 0;
}
output:
1 2 0
2 2 2
Process returned 7 (0x7) execution time : 0.081 s
Press any key to continue.
To understand the logic behind your output, you need to have an idea of Pointer and how it works.
The C language exhibits an undefined behavior (https://en.wikipedia.org/wiki/Undefined_behavior) where you can't predict the way the syntax will work on the execution.
i++ -> increments i, but returns the previous value of i.
++i-> increments i, and returns the new value of i after assignment.
i = i + 1 -> adds 1 to i, writes it to i, and then returns the new value of i after assignment.
Refer this link for more info: https://en.wikipedia.org/wiki/Sequence_point
Based on this principle, the output can be analyzed as below.
int i=0;
printf("%d %d %d \n",i++,i,i++);
Firstly, i=0
it starts execution from the right side i++
First, it assigns the value& the pointer stores 0; then the increment will take place. So, i=1.
In the next step, there is only a variable. So, the pointer doesn't store the value; it only stores the address. Therefore, i=1.
Last step execution is the same as the first step. So, i=2.
Now, it will print the stored value. So, the output is 1 2 0.
Now, let's analyze the second OUTPUT.
In the second output, the expression is j=j+1.
So, first, it executes all the steps and then prints the value.
So, the second output is 2 2 2.
I hope you now got the difference between i++ & i=i+1.
Related
I have been going through some exercises from a recommended book I found on this website. I came across this following basic piece of code, which I could not fully understand.
#include <stdio.h>
int main(void)
{
int i;
for (i = 10; i >= 1; i /= 2)
printf("%d ", i++);
return 0;
}
This is my reasoning behind this program fragment:
Variable i is initialised to 10.
i is tested to see if greater or equal to 1, (which is always the case).
The third expression reads: i = i / 2, thus i is divided by 2 and its value stored in i.
In the printf statement i is incremented after each printf statement.
I simply cannot understand why the output of this program is:
1 1 1 1 1 1 1 1 ...
I get that the condition statement is always true, however shouldn't the first values be:
5 3 2 1 1 1 1 1?
Basically I cannot seem to understand why the value of i is straight away being stored as 1. Any corrections regarding my reasoning and/or insight on the matter will be appreciated. Please do excuse the basic nature of this question.
As #abelenky pointed out, the correct output is 10 5 3 2 1 1 1 .... The only mistake you made in your reasoning is that the statement i /= 2 gets evaluated after the body of the for loop, before testing the condition again. Another way to write the same loop would therefore be
for(i = 10; i >= 1; i = (i + 1) / 2)
printf ("%d ", i);
If you are running on Windows, try paging the output through more: myprog | more. This should allow you to see the beginning of the output of this infinite loop. On a linux machine, you could acheive the same result using more or less: myprog | less. Thanks to #EugeneSh for making the suggestion that this could be the issue.
Another way that I have found to view the initial output for programs like this is to hit Ctrl+C immediately after starting the program with Enter. This is not a "standard" method and may require very quick reflexes to get any results for a quick loop like yours.
A final suggestion is to limit the output you produce from the program directly:
int i, count;
for(i = 10, count = 0; i >= 1 && count < 100; i /= 2, count++)
printf("%d ", i++);
This will add a counter that will stop your output after 100 numbers have been printed and allow you to see the first numbers.
On the second line, you have 'i++'.
Thus at each iteration of the loop, it will also increment i by 1.
So supposing i = 1 when you start the loop. First it will be divided by 2 (i /= 2). Since i is an integer, it will become 0. Then, on the second line, you have 'i++', thus incrementing i.
So by the end of the loop iteration, i will be back to being equal to 1 (thus making this loop infinite).
Please explain me why the last printf gives value 11?
I really don't understand why it happened.
When a = 10 the condition is not fulfilled so why this value has changed to 11?
Incrementation goes as soon as the condition is checked?
Code:
int main(void) {
int a = 0;
while(a++ < 10){
printf("%d ", a);
}
printf("\n%d ", a);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
11
Let's look at a++ < 10 when a is equal to 10.
The first thing that will happen is 10 < 10 will be evaluated (to false), and then a will be incremented to 11. Then your printf statement outside the while loop executes.
When the ++ comes on the right hand side of the variable, it's the last thing evaluated on the line.
Try changing a++ < 10 to ++a < 10, rerunning your code, and comparing the results.
The post increment operator increments the value of the variable before it after the execution of the statement.
Let's take an example,
int k = 5 ;
printf("%d\n", k++ );
printf("%d", k );
will output
5
6
because in the first printf(), the output is shown and only after that, the value is incremented.
So, lets look at your code
while(a++ < 10)
it checks a < 10 and then after that, it increments a.
Lets move to a few iterations in your loop.
When a is 9, the while loop checks 9 < 10 and then increments a to 10, so you will get output for that iteration as 10, and similarly, for the next iteration, it will check 10 < 10 but the while loop does not execute, but the value of a is incremented to 11 and thus, in your next printf() , you get output as 11.
Let's look at a simpler piece of code to show what a++ does.
int a = 0;
int b = a++;
printf("%d %d\n", a, b);
I think that you'd expect this to output 1 1. In reality, it will output 1 0!
This is because of what a++ does. It increments the value of a, but the value of the expression a++ is the initial pre-incremented value of a.
If we wanted to write that initial code at the top of my answer as multiple statements, it would actually be translated to:
int a = 0;
int b = a;
a = a + 1;
printf("%d %d\n", a, b);
The other increment that we have access to is pre-increment. The difference there is that the value of the expression ++a is the value of a after it was incremented.
Because it's post-increment. The compiler will first evaluate a<10 and THEN increment a by 1.
I am learning recursion now-a-days. Here are three codes. The first and third is giving me the expected output but the second is not? Can somebody tell me what is just the difference in them.
Code 1:
void tail(int i){
if (i>0) {
printf("%d\n",i);
tail(i-1);
}
}
int main()
{
tail(5);
}
Code 2:
void tail(int i){
if (i>0) {
printf("%d\n",i);
tail(i--);
}
}
int main()
{
tail(5);
}
Code 3:
void tail(int i){
if (i>0) {
printf("%d\n",i);
tail(--i);
}
}
int main()
{
tail(5);
}
output of Code 1:
5
4
3
2
1
output of Code 2:
5
5
5
.
.
. Infinite
output of Code 3:
5
4
3
2
1
Please help me out. I am confused!
Result is as expected
decrement is post decrement so it would first use current value and then decrement. So function gets repeatedly called with current value so infinite loop.
Working fine for me . Similar to first
Of course code number 2 won't. In code number 2 you typed tail(i--); what -- operator (after the variable name) does is first using him in the line you requested and THEN decrease him by one.
Let's say I have the line printf("%d", i--); It'll print i in it's current value and only after printing it, it will be decreased, it first uses I, and then decreases it - same would happen if you would just type:
printf("%d", i);
i--;
About the -- operator BEFORE the variable. It'll first decrease and then do the requested action - so printf("%d", --i); will decrease i by one and then print it.
We all agree code 1 works well, code 2 actually is in an infinite loop BECAUSE you decrease the variable AFTER calling the function - so it decreases in one function only.
Basically, what it does is like:
printf("%d", i); //which is 5
tail(i);//which is still 5
i--; //will never get to this line because we called another function with variable 5
and so on.
About code number 3, it works perfectly, it's like code number 1 (but code number one won't actually decrease the variable, just call the function with the variable-1).
EDIT:
for more information, you can search in this article :)
The 3 have to work. The 2 don't work because i is decremented after been passed to the function.
You should work with pointers in second case. Each time you are passing the same value into recursive function ... first goes function call and after that you have decrement operation. As a result you have the same value (5) in each recursive call.
The second doesn't give you your desired output because you are using post-decrement operator i--.
This means "use i and then decrement i" as opposed to --i which means "decrement i and then use i".
So in your third case, i whose value is 5, gets decremented to 4, and then tail(4) is called.
In the second case, tail(i--) is called, which means call tail(5) and then do i-=1; .
If i-- and --i are given as standalone statements, they are equivalent, for example
for(int i=5;i>0;i--)
is effectively the same as
for(int i=5;i>0;--i)
But in cases such as follows:
int i=5;
int a=i--;
printf("%d %d", i, a);
This gives out put 4 5 whereas
int i=5;
int a=--i;
printf("%d %d", i, a);
will give output 4 4.
This question already has answers here:
What is the difference between ++i and i++?
(20 answers)
Closed 9 years ago.
Why is i++ and ++i same in the following code?
#include <stdio.h>
int main()
{
int i=5;
while(1)
{
i++; /*replacing i++ by ++i also gives 6*/
printf("%d",i);
break;
}
return 0;
}
The output is 6. I learnt that the increment operator i++ has its value the current value of i and causes the stored value of i to be incremented.But i's value is displayed as 6 though the current value of i is 5. Replacing i++ by ++i also gives the same value 6. Why is i++ and ++i same in this case and why output is 6 though initial value is 5.
The order of execution is sequential.
i++ or for that matter ++i is a single instruction to be executed at that sequence point, with i's value not being used anywhere at that instruction, so it doesn't really matter.
If you do replace printf("%d",i); with printf("%d",i++); or printf("%d",++i); things will be much different.
EDIT: I also discovered something that is fairly useful to know. In C and C++, the prefix unary operator returns an lvalue, in contrast to the postfix unary operator, so if you want to, for example, decrement i twice, then
(i--)--; // is illegal
whereas
(--i)--; // is perfectly legal and works as intended.
Check out the answer I found at What is the difference between ++i and i++?
"++i will increment the value of i, and then return the incremented value."
"i++ will increment the value of i, but return the original value that i held before being incremented."
You don't use value which it returns, so it does not matter in your case.
It only changes what value will be set when used in a method.
With i++ you'll use i in the method, once done i will be increased.
With ++I first you increase the value and then you use it in the method.
i++ - add 1 to i returns the old value.
++i - add 1 to i, returns the new value.
In your case :
i++ - returns 5 and add 1 to i make i as 6. If you catch the
return value of i++ you can get the clear idea. because return will have the value 5.
++i - add 1 to i and make i as 6 then return i=6
Sample code:
#include <stdio.h>
int main()
{
int i=5;
while(1)
{
int post, pre;
post = i++;
printf("post : %d, i: %d\n", post, i);
i = 5;
pre = ++i;
printf("pre : %d, i: %d\n", pre, i);
break;
}
return 0;
}
Output:
post : 5, i: 6
pre : 6, i: 6
int i = 5;
i++; // implies i = i + 1 ==> 6
// Even ++i results the same
printf("%d",i); // Obviously it prints 6
If you don't assign the returned value to a variable or use it as an argument, the result is the exact same.
The primary difference between the two is that ++i increments the variable and only then assigns the value, while i++ assigns first and increments afterwards.
#include<stdio.h>
main
{
int x[]={1,2,3,4,5};
int i,*j;
j=x;
for(i=0;i<=4;i++)
{
printf("%u",j);
j++;
}
}
output:
65512
65514
65516
65518
65520
But when I change the printf to"
printf("%u",&j[i]);
Output is:
65512
65516
65520
65524
65528
Why the address differ by 2 in first case and 4 in second casee?
What is wrong with just printing j and printing &j[i]?
You get jumps of 4 in the second example because you are incrementing j and offsetting by i! Both of these contribute a difference of 2.
Note also that printf is not type-safe; it is up to you to ensure that the arguments match the format-specifiers. You have specified %u, but you've given it an int *, you should use %p for pointers.
First, just to make it clear, you are printing the pointer j, and not the pointed value, *j
Now, regarding the printed address. In your second example:
for(i=0;i<=4;i++)
{
printf("%u",&j[i]);
j++;
&j[i] equals to (j+i). i is incremented in each iteration, which contributes 2 to the pointer's value, and j is incremented too, which contributes another 2.