1

I have tried to do some practice with vector, and I made a simple for loop to calculate the sum of the elements within the vector. The program did not behave in the way I expect, so I try to run a debugger, and to my surprise, somehow, the compiler skips the for loop altogether, and I have not come up with a reasonable explanation.

//all code is written in cpp
#include <vector>
#include <iostream>
using namespace std;

int simplefunction(vector<int>vect)
{
   int size = vect.size();
   int sum = 0;
   for (int count = 0; count == 4; count++) //<<--this for loop is being skipped when I count==4
   {            
      sum = sum + vect[count];
   }
   return sum;  //<<---the return sum is 0 
}

int main()
{
   vector<int>myvector(10);
   for (int i = 0; i == 10; i++)
   {
      myvector.push_back(i);
   }
   int sum = simplefunction(myvector);
   cout << "the result of the sum is " << sum;    
   return 0;

}

I have done some research, and usually the ill-defined for loop shows up when the final condition cannot be met (Ex: when setting count-- instead of count++)

Boann
  • 48,794
  • 16
  • 117
  • 146
James
  • 57
  • 3

1 Answers1

4

Your loop's conditions are wrong, as they are always false!

Look at to the loops there

for (int i = 0; i == 10; i++) 
//              ^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)

and

for (int count=0; count==4; count++)
//                ^^^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)

you are checking i is equal to 10 and 4 respectively, before incrementing it. That is always false. Hence it has not executed further. They should be

for (int i = 0; i < 10; i++) and for (int count=0; count<4; count++)


Secondly, vector<int> myvector(10); allocates a vector of integers and initialized with 0 s. Meaning, the loop afterwards this line (i.e. in the main())

for (int i = 0; i == 10; i++) {
    myvector.push_back(i);
}

will insert 10 more elements (i.e. i s) to it, and you will end up with myvector with 20 elements. You probably meant to do

std::vector<int> myvector;
myvector.reserve(10) // reserve memory to avoid unwanted reallocations
for (int i = 0; i < 10; i++) 
{
    myvector.push_back(i);
}

or simpler using std::iota from <numeric> header.

#include <numeric> // std::iota

std::vector<int> myvector(10);
std::iota(myvector.begin(), myvector.end(), 0);

As a side note, avoid practising with using namespace std;

JeJo
  • 30,635
  • 6
  • 49
  • 88