Hello people.
I was just wondering what the differences are when I put the ++ in the front or the end. I have tried to find the difference using (for or while) for example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream>
usingnamespace std;
int main()
{
int count = 0 ;
int n = 20 ;
while (n>0)
{
++count ; // or count++
n-- ; // or --n
cout << count << endl ;
cout << n << endl ;
}
cout << count << " " << n ;
return 0;
}
But using ++count or count++ gave me the same answer. So what is the main difference between these two, and when is it mostly used for ??
pre- and post- increment/decrement will only really make a difference when you use the variable to do something else with in the same expression.
With pre-increment, the variable will be incremented and then used for the evaluation. With post increment, it is used at its current value and then incremented after the expression is evaluated.
#include<iostream>
usingnamespace std;
int main()
{
int count_1 = 0 ;
int count_2 = 0 ;
int n = 20 ;
while (n>0)
{
--n ;
cout << ++count_1 << endl ;
cout << count_2++ << endl ;
cout << endl ;
}
cout << "final value for count_1 = " << count_1 << endl ;
cout << "final value for count_2 = " << count_2 << endl ;
cout << endl ;
return 0;
}
There can be a slight performance penalty when using the post-increment with classes, rather than native types. For this reason, I tend to stick to the pre-increment unless I actually need the post-increment behaviour for a particular algorithm.
But for for() loops, I think people are equally divided. With maybe a greater tendency for C programmers to use post-increent in this case?
andy's right.
pre-increment/decrement means 'first increase/decrease and then use the value'.
whereas post-increment/decrement means 'first use the value and then increase/decrease'.
hope this makes it simple for u.
why b equal '0' if i used post-increment ?
i made in the paper and result was 1.
can someone help me ?
thanks...
this statement:
b= a++ + a++;
Is equal to saying
1 2
b = 0;
a+=2;
So when you output b its going to be 0.
You are using using post-increment, so its first going to assign the value of a + a(Which is 0) to b.
It then increments a. So a is after the statement equal to 2 and b is 0.
int a =0, b=0;
b= a++ + a++;
cout<<"valor de b = "<< b;
why b equal '0' if i used post-increment ?
i made in the paper and result was 1.
The line b= a++ + a++; is an error in C++ (and in C, for that matter, but not in Java). The behavior of the program that has this line, if it is compiled, is undefined, and any reasoning about it is meaningless.
The difference between ++count and count++ is that you can use any even number of pluses before the count while after the count you may use only two pluses.:)
For example.