Increment ++i, i++ and i+=1 - c++

I am beginner in C++. What I understand is that:-
i++ is executing first, then increment, ++i is increment first, then execute,i+=1 is increment by 1,then execute. But in the FOR loop:
for (i=0;i<10;i++)
for (i=0;i<10;++i)
There is really no difference in these two loops above.
Here is another one to calculate the sum of all integers from 1 to 100:
int i=1, sum=0;
while (i<=100)
{
sum+=i;
i++; //i+=1; ++i;
}
cout<<sum<<" "<<i<<endl;
return 0;
But if I replace i++ with i+=1 or ++i, they all return a sum of 5050 and i of 101. So I really don't see any difference in them.
So could anyone explain this to me? Which one of those is used most in programming? Thank you!!

You are correct. In your examples there is no difference.
But here there is:
int i = 0;
cout << i++ << endl; //prints 0
cout << i << endl; //prints 1
vs
int i = 0;
cout << ++i << endl; //prints 1
cout << i << endl; //prints 1
Which one of those is used most in programming?
Most of the time, ++ is the only operation in the statement (FYI, a for loop has three statements).
If it isn't, then it might matter, and you'll use whichever one gives you the correct behavior.
FYI
Some developers have the opinion that if pre and postfix operators should always be used alone (not part of a large statement). They can lead to confusing code, or even undefined behavior.
For example,
int i = 0;
cout << i++ + i++ << endl;
has undefined behavior.

So could anyone explain this to me?
What i++ does is return the current value of i and then increment it by one, and ++i first increment i by 1 and then returns the value of i.
Take a look at this, for example:
i = 5;
j = 5;
res = i++; //res = 5, but i=6
res = ++j; //res = 6 and j=6
Which one of those is used most in programming?
Both are used depending on what you want or may be how you want.
One more thing to note:
++i is an l-value, but i++ is not. For details see here

Your analysis is correct. i++ will return the value of i, then increment, whereas ++i will increment the value of i, then return the new value. i += 1 will do the same as ++i. The difference in where they will be used in actual code is primarily situational; there's no specific answer as to where each of them are most often used or helpful. It all depends on what you want to do.
Here's a contrived example of one time it might be useful to use post-increment (i++ form):
// Return the length of a string, including the null byte
int stringLength(char str[])
{
int length = 0;
while (str[length++] != 0);
return length;
}
If you wanted to return the length without the null byte, you could modify the above example slightly, using the ++i form:
// Return the length of a string, without the null byte
int stringLength(char str[])
{
int length = -1;
while (str[++length] != 0);
return length;
}
As for i += 1, I don't think I've ever done quite that, since you can use pre- or post-increment instead. I've generally only used the compound assignment operators for values other than 1.

I think if you imagine how the for loop works you can understand the problem at hand.
for loop
initialization --> i = 0
<check condition> --> i<10? ------->--------------------
| | |
^ |yes(i.e condition not met) |no(i.e condition met)
| V V
| --------------
| |body of loop|
| --------------
| |
| V
-------<------------increment i (**) exit for loop
** increment i means i++ or ++i
i++ can be replaced by this :
int temp = i;
i = i + 1;
temp will be useless here so the compiler will optimize it to just inc i instruction. even if it doesn't do that temp is just a waste of space that's all.
++i can be replaced by
i = i + 1;
int temp = i;
again temp is not required so the compiler will just replace it with inc i instruction.
if you see both the instruction are the same because they are not being assigned to anything. only i is being affected by the increment. so both are essentially the same. this is true if i is a built-in type .
you see that the increment instruction is placed after the body of the loop? can you now see that this is almost similar to the while loop that you showed?
it is always nice to think of loops in this way.

Related

Is i++ or ++i better for this program?

i'm trying to create a program which checks if input is is an int or a string.
This is the code:
// CPP program to check if a given string
// is a valid integer
#include <iostream>
using namespace std;
// Returns true if s is a number else false
bool isNumber(string s)
{
for (int i = 0; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
// Driver code
int main()
{
// Saving the input in a string
string str = "6790";
// Function returns 1 if all elements
// are in range '0-9'
if (isNumber(str))
cout << "Integer";
// Function returns 0 if the input is
// not an integer
else
cout << "String";
}
I wanted to ask that whether i++ or ++i is better for this loop and why?
for (int i = 0; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
THANK YOU!
I prefer the form ++i in C++, because i may be an iterator or other object with overloaded operator++. In those cases, the form i++ generates a temporary object to hold the previous value of i, while the form ++i does not. The compiler may optimize away that temporary object, but it’s not required to, and in some cases may not be allowed to.
So, ++i is slightly better than i++ as the former need not retain the initial value and recheck it. It is one of the very few instances where time optimization and memory optimization occur simultaneously. But the difference is too small to be noted, just 4 bytes. Also, the time difference is negligibly small.
You would essentially get the same answer in your example but might receive a minute time and memory optimization while using ++i.
Since the datatype of i is int, it doesn't matter if you use i++ or ++i.
If its a large class iterator, ++i is faster than i++. Its a good practice to use ++i.

Is this code undefined behavior due to accessing out of bound element in the first for loop?

Is this code undefined behavior due to accessing out of bound element in the first for loop?
int main() {
std::size_t length = 4;
int* a = new int[length];
for (std::size_t i = 0; i < length; )
a[i] = ++i;
for (std::size_t i = length - 1; i >= 0; i--)
std::cout << a[length - 1] << " ";
}
If shrotly, yes, it is. In this situation C++ doesn't define in which order expression must be calculated, because both sides have side effects. So one compiler can firstly calculate left side, second can calculate at first right side. But if you look at this, you can find that
a[i] = i++; // undefined behavior until C++17
So, you can use this line, only if you use C++ 17.

Indexing issue with a for loop

I have a for loop where I'm using the slide operator as I'm working with unsigned types. Essentially it boils down to
for (std::size_t i = 6; i --> 0;){
cout << i;
}
But it outputs the numbers from 5 to 0 inclusive and omits 6. Why?
Thank you very much for looking at this. I'm quite stuck.
This is a touchstone for
The fact that this so-called "operator" should be used with caution, if at all.
Changing the state of variables within the conditional check of a for loop ought to be done with extreme caution, if at all.
The largest output is 5 simply because i is decremented as a result of the conditional test which also decrements i. The conditional check is ran before program control enters the for loop body.
You really ought to rewrite the loop. Don't set the initial value of i to 7 as that's a dirty hack. Although --> is often used with while (and to emphasise, it's unlikely to win you many friends in your programming review), I've never seen it used with a for loop before.
--> is not a slide operator.
It is understood by the compiler as two different operators -- and >.
So your code look like this to the compiler:
for (std::size_t i = 6; (i--) > 0;){
cout << i;
}
Since the loop condition is checked before entering the loop's body i is decreased before the first execution of the loop's body, hence the produced sequence of numbers is 5 4 3 2 1 0.
For more details see this Stack Overflow question: What is the "-->" operator in C++?
After evaluating this condition in the for statement
i --> 0
i will be equal to 5. So the first iteration of the loop outputs
5
To achieve the effect you want rewrite the loop the following way
#include <iostream>
int main()
{
size_t i = 6;
do
{
std::cout << i;
} while ( i-- > 0 );
return 0;
}
The program output is
6543210
Another way is the following
#include <iostream>
int main()
{
for ( size_t i = 6; std::cout << i && i != 0; i-- )
{
//
}
return 0;
}
Of course you could write the loop like this
const size_t N = 6;
for ( size_t i = N + 1; i-- > 0; )
// ^^^^^^^
{
std::cout << i;
}
However in general this approach does not work when the initial value of i is equal to std::numeric_limits<size_t>::max() Because if to add 1 to this value you will get 0.
A general approach using a for loop can look the following way
#include <iostream>
int main()
{
const size_t N = 6;
for ( size_t i = N, j = N; j != 0; j = i-- )
{
std::cout << i;
}
return 0;
}
Its output is
6543210

Problems with a simple while loop

I'm on the "looping while" segment of a book named c++ programming written by Mike McGrath.
In the book it explains how a while loop works and what it can and cannot do etc. It gives an example code which I understand for the most part except for something that the book does not explain and I was wondering if any of you could explain it.
This is the code:
#include <iostream>
#include <vector>
using namespace std ;
int main(){
vector <int> vec(10) ;
int i = 0 ;
while (i < vec.size()){
i ++ ;
vec[i-1] = i ;
cout << " | " << vec.at(i-1) ;
}
}
Now, this is the way I am reading this, and I'm sure I'm reading it the wrong way because the results make no sense to me:
While i is less than 10 (vector's size) continue executing this code. So integer i is 0, but it increments to 1 at the beginning of the code. Next however, is the part I am so confused about.
It says vec[i-1], why is he subtracting 1? And then making it equal to i? If I try to make it vec[i] = i; the program crashes. So the way I am reading it is, vec[i - 0 ] would have to be 0 since 0 was just incremented to 1 on the previous step of the while loop. Then to display the results he once again calls the command vec.at() to i-1, which further confuses me. I simply do not understand what the -1 means within the vector. Shouldn't what's inside the brackets mean the position within the vector?
Because in the first line of the loop body he's incremented i (making it 1 on the first iteration), so he needed to subtract 1 to get back to valid array indexing (whereby 0 is the first index of an array, and n-1 is the last).
The program crashes when you change that, because you'd be accessing vec[1] to vec[N] (where N is the vector size) instead of vec[0] to vec[N-1], the real valid range of the vector.
He's assigning i so that each vector element contains an incrementing count. It's a bit confusing.
vec[0] = 1
vec[1] = 2
vec[2] = 3
...
vec[9] = 10
It would be better written like this:
int i = 0;
while (i < vec.size()) {
vec[i] = i+1;
cout << " | " << vec[i];
i++;
}
or:
for (int i = 0; i < vec.size(); i++) {
vec[i] = i+1;
cout << " | " << vec[i];
}
As Lightness has pointed out, he need to substract 1 to get back to 0 based indexing. The loop is same as below.
vector<int> vec(10);
int i = 0;
while(i < vec.size())
{
vec[i] = i + 1;
cout << " |" << vec.at(i);
i++;
}
that's why the output printed 1 to 10.
within the vector, [i-1] means minus current value of i by 1 then assign the value as index to vector. (note: the substracted value is not assigned back to i)
same description as above for vec.at(i-1)

Does the following code invoke Undefined Behavior?

#include <iostream>
#include <cmath>
#define max(x,y) (x)>(y)? (x): (y)
int main() {
int i = 10;
int j = 5;
int k = 0;
k = max(i++,++j);
std::cout << i << "\t" << j << "\t" << k << std::endl;
}
No, it doesn't.
In this case the situation is saved by the fact the ?: operator has a sequence point immediately after evaluating the first operand (the condition) and after that only one of the two expressions (second or third operand) is evaluated. Your code is equivalent to
...
bool c = i++ > ++j;
k = c ? i++ : ++j;
...
No undefined behavior here.
Well, there certainly are a lot of problems with it.
max is actually computing min
increment operators are doubled on whatever choice is selected since you are using a macro
using postfix/prefix increments is just thrown in to confuse, but doesn't have a lot of bearing on the problem.
This code will produce the same results each time run, so no, it's not undefined. At the cout:
i = 11
k = 7
j = 7
This sounds like a bad homework problem. :)